NGINX Proxy not working with HTTP/2 and gRPC - nginx

I am trying to use NGINX as an "API Gateway" into my gRPC services - all within a Kubernetes Cluster. A Typescript React App is just making calls via the grpc-web module to an Envoy proxy, then to the API NGINX Proxy. (I have tested that end of the stack - and I'm 100% sure that envoy works fine).
NOTE: I may be making a mistake NOT using TLS with the Envoy Proxy (Which is the 'client' to NGINX) - so please comment if that's the mistake I'm making
For this to work with my gRPC endpoints, I need to enable HTTP/2 proxying (this is required for gRPC to work - it must be over HTTP/2). And so, following the official NGINX Documentation which is here: https://www.nginx.com/blog/nginx-1-13-10-grpc/ , my nginx.conf file looks like:
worker_processes auto;
events {}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent"';
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 1449 ssl http2;
ssl_protocols TLSv1.2;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
ssl_prefer_server_ciphers on;
ssl_certificate ./server.crt;
ssl_certificate_key ./server.key;
location /com.example.grpcService {
grpc_pass grpcs://api-grpc-server:9090;
proxy_buffer_size 512k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 512k;
grpc_set_header Upgrade $http_upgrade;
grpc_set_header Connection "Upgrade";
grpc_set_header Connection keep-alive;
grpc_set_header Host $host:$server_port;
grpc_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
grpc_set_header X-Forwarded-Proto $scheme;
}
}
}
I also heard from another forum that you MUST use TLS/SSL with HTTP/2 or it won't work, so I first tried it without - it didn't work. Then I tried it with the generated SSL certificates and it looks like I'm still getting a 400 error from the proxied service. The log looks like:
172.17.0.17 - - [05/Jan/2021:18:16:23 +0000] "PRI * HTTP/2.0" 400 157 "-" "-"
I have used OpenSSL for the certificates which resulted in .crt and .key files being generated - which I then used for BOTH my Spring Boot gRPC Server & NGINX Proxy. My OpenSSL version is OpenSSL 1.1.1c 28 May 2019.
I am using those same certificates on the actual gRPC Server itself, this looks like:
#Component
public class GrpcServerRunner implements CommandLineRunner, DisposableBean {
private final ConfigurableApplicationContext applicationContext;
private Server server;
public GrpcServerRunner(#Autowired ConfigurableApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#Override
public void run(String... args) throws Exception {
File cert = new File("~/etc/ssl/server.crt");
File key = new File("~/etc/ssl/server.key");
BindableService service = applicationContext.getBean("grpcService", BindableService.class);
server = ServerBuilder.forPort(9090).useTransportSecurity(cert, key).addService(service).build();
runSever();
}
private void runSever() {
Thread thread = new Thread(() -> {
try {
server.awaitTermination();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.setDaemon(false);
thread.start();
}
#Override
public void destroy() {
server.shutdown();
}
}
I'd really appreciate any help, questions, feedback or solutions to this problem - so thanks in advance.

It actually had nothing to do with the gRPC Server or the Java Project.
Here's the root NGINX config file:
worker_processes auto;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr [$time_local] [$time_local] [$cookie_X-AUTH-TOKEN] '
'"$scheme $host $request" $status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'($request_time)'
'(($sent_http_set_cookie))';
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
# Upstream servers here
upstream api-server-address {
server api-server-address:9090;
keepalive 20;
}
# gRPC Client requirements set
client_max_body_size 0;
proxy_request_buffering off;
server {
listen 1449 http2;
include ./config/grpc-header-config.conf.conf;
# gRPC service proxied here
location /com.yourpackage {
auth_request_set $upstream_http_set_cookie;
auth_request_set $upstream_http_status;
grpc_pass grpc://api-service-address;
include config/grpc-header-config.conf;
}
default_type application/grpc;
}
}
The key file that made this work was this one (this is the one referenced by the root one in config/grpc-header-config.conf):
error_page 400 = #grpc_internal;
error_page 401 = #grpc_unauthenticated;
error_page 403 = #grpc_permission_denied;
error_page 404 = #grpc_unimplemented;
error_page 429 = #grpc_unavailable;
error_page 502 = #grpc_unavailable;
error_page 503 = #grpc_unavailable;
error_page 504 = #grpc_unavailable;
error_page 405 = #grpc_internal;
error_page 408 = #grpc_deadline_exceeded;
error_page 413 = #grpc_resource_exhausted;
error_page 414 = #grpc_resource_exhausted;
error_page 415 = #grpc_internal;
error_page 426 = #grpc_internal;
error_page 495 = #grpc_unauthenticated;
error_page 496 = #grpc_unauthenticated;
error_page 497 = #grpc_internal;
error_page 500 = #grpc_internal;
error_page 501 = #grpc_internal;
location #grpc_deadline_exceeded {
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Transfer-Encoding,Custom-Header-1,X-Accept-Content-Transfer-Encoding,X-Accept-Response-Streaming,X-User-Agent,X-Grpc-Web,Access-Control-Allow-Credentials';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Set-Cookie' $auth_cookie;
add_header 'Access-Control-Expose-Headers' 'Content-Transfer-Encoding,Grpc-Message,Grpc-Status';
add_header 'Access-Control-Allow-Origin' *';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'grpc-status' 4;
add_header 'grpc-message' 'deadline exceeded';
return 204;
}
location #grpc_permission_denied {
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Transfer-Encoding,Custom-Header-1,X-Accept-Content-Transfer-Encoding,X-Accept-Response-Streaming,X-User-Agent,X-Grpc-Web,Access-Control-Allow-Credentials';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Set-Cookie' $auth_cookie;
add_header 'Access-Control-Expose-Headers' 'Content-Transfer-Encoding,Grpc-Message,Grpc-Status';
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'grpc-status' 7;
add_header 'grpc-message' 'permission denied';
return 204;
}
location #grpc_resource_exhausted {
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Transfer-Encoding,Custom-Header-1,X-Accept-Content-Transfer-Encoding,X-Accept-Response-Streaming,X-User-Agent,X-Grpc-Web,Access-Control-Allow-Credentials';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Set-Cookie' $auth_cookie;
add_header 'Access-Control-Expose-Headers' 'Content-Transfer-Encoding,Grpc-Message,Grpc-Status';
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'grpc-status' 8;
add_header 'grpc-message' 'resource exhausted';
return 204;
}
location #grpc_unimplemented {
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Transfer-Encoding,Custom-Header-1,X-Accept-Content-Transfer-Encoding,X-Accept-Response-Streaming,X-User-Agent,X-Grpc-Web,Access-Control-Allow-Credentials';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Set-Cookie' $auth_cookie;
add_header 'Access-Control-Expose-Headers' 'Content-Transfer-Encoding,Grpc-Message,Grpc-Status';
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'grpc-status' 12;
add_header 'grpc-message' unimplemented;
return 204;
}
location #grpc_internal {
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Transfer-Encoding,Custom-Header-1,X-Accept-Content-Transfer-Encoding,X-Accept-Response-Streaming,X-User-Agent,X-Grpc-Web,Access-Control-Allow-Credentials';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Set-Cookie' $auth_cookie;
add_header 'Access-Control-Expose-Headers' 'Content-Transfer-Encoding,Grpc-Message,Grpc-Status';
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'grpc-status' 13;
add_header 'grpc-message' 'internal error';
return 204;
}
location #grpc_unavailable {
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Transfer-Encoding,Custom-Header-1,X-Accept-Content-Transfer-Encoding,X-Accept-Response-Streaming,X-User-Agent,X-Grpc-Web,Access-Control-Allow-Credentials';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Set-Cookie' $auth_cookie;
add_header 'Access-Control-Expose-Headers' 'Content-Transfer-Encoding,Grpc-Message,Grpc-Status';
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'grpc-status' 14;
add_header 'grpc-message' 'unavailable';
return 204;
}
location #grpc_unauthenticated {
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Transfer-Encoding,Custom-Header-1,X-Accept-Content-Transfer-Encoding,X-Accept-Response-Streaming,X-User-Agent,X-Grpc-Web,Access-Control-Allow-Credentials';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Set-Cookie' $auth_cookie;
add_header 'Access-Control-Expose-Headers' 'Content-Transfer-Encoding,Grpc-Message,Grpc-Status';
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'grpc-status' 16;
add_header 'grpc-message' '401. Unauthorized.';
return 200;
}
I realize this looks super sketchy/hacky, but that's the only way I could do it. Feel free to improve this answer!
Your essentially setting the default protocol to gRPC and HTTP/2, then on any error page you just reset the statuses to match the gRPC conventions + spec so that your client will be able to parse the binaries. If you are using SSL with this, you just need to put the certificates on each side as normal, then change the grpc_pass to grpcs://api-server-address instead of what I have.
Feel free to add any constructive feedback or any questions! Cheers, Ben

Related

dash.js - stuck at buffering when trying to watch (new) live stream

This is my setup:
I have a webpage which uses dash.js to view a live stream. The live stream is coming from my computer which is running OBS and NGINX. This works without a problem except when I call up the webpage within the first 30 seconds (or so) after the stream has started.
I tell dash to open up index.mpd on my computer, but only when it's available. In pseudo code:
START: If index.mpd is available
initialize stream and view it
Else
go to START
End
As soon as index.mpd is available, this means there's also a video/audio chunk available so it should be able to start playing. But it stalls instead (grey screen with rotating pin wheel). This probably has to do with the fact the settings ask for a 20 second buffer and a video/audio chunk is 8.3 seconds. (BTW, I have no idea why those chunks are 8.3 seconds - I could not find a setting anywhere in OBS or NGINX that reflects those 8.3 seconds)
The problem is, it never stops stalling (is it trying to buffer? I don't know). Even when all chunks are available and NGINX starts FIFO-ing the chunks. It never recovers from the stall.
Only when I open the page at a time when the entire buffer is available (which, again for some unknown reason, is about 30 seconds instead of the 20 I have set it to) will it start (dis)playing the stream.
Here is the complete NGINXG.conf:
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
rtmp {
server {
listen 1935;
chunk_size 4096;
application live {
live on;
interleave on;
meta on;
session_relay on;
max_connections 1500;
record_path recordings;
record_suffix all-%d-%b-%y-%T.flv;
push rtmp://localhost/dash;
}
application dash {
live on;
dash on;
dash_nested on;
dash_cleanup on;
dash_fragment 5s;
dash_playlist_length 20s;
dash_path temp/tmp_dash;
}
}
}
http {
keepalive_timeout 60;
send_timeout 10;
keepalive_requests 10;
client_body_timeout 10;
sendfile on;
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
server {
listen 8050;
server_name localhost;
access_log logs/host.access.log main;
add_header Strict-Transport-Security "max-age=63072000;";
index index.php index-nginx.html index.html index.htm;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root site;
}
location / {
location ~* \.m3u8$ {
add_header Cache-Control no-cache;
}
try_files $uri $uri/ =404;
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Strict-Transport-Security' 'max-age=31536000';
add_header 'X-Content-Type-Options' "nosniff" 'always';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
# add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
root site;
index index.php index.html index-nginx.html index.htm index.m3u8 index.mpd;
}
location /stat {
rtmp_stat all;
rtmp_stat_stylesheet stat.xsl;
}
location /stat.xsl {
root site;
}
location /tmp_dash {
alias temp/tmp_dash;
autoindex on;
autoindex_localtime on;
autoindex_exact_size off;
expires -1;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length';
}
types {
application/dash+xml mpd;
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
text/html html;
}
}
}
}
And here's the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="http://cdn.dashjs.org/latest/dash.all.min.js"></script>
<script>
window.addEventListener( "load", init );
var XMLHttp;
var streamActive = false;
var url = "/tmp_dash/stream/index.mpd";
function init(){
XMLHttp = new XMLHttpRequest();
XMLHttp.onreadystatechange = function() {
if( XMLHttp.readyState == 4
if( XMLHttp.status == 200 ) {
// Index.mpd exists
if( ! streamActive ) {
player = dashjs.MediaPlayer().create();
player.initialize( document.querySelector( "#videoPlayer" ), url, true);
}
} else if( XMLHttp.status == 404 ) {
setTimeout( checkStreamReady, 5000 ); // Check again in 5 seconds
}
}
}
checkStreamReady();
}
function checkStreamReady() {
XMLHttp.open( "GET", url, true );
XMLHttp.send();
}
</script>
</head>
<body>
<div id="videocontainer">
<video id="videoPlayer" controls></video>
</div>
</body>
</html>

Nginx with auth_request_module to reverse proxied app throws CORS errors

I am developing a nginx server to work as a reverse proxy to a local webapp only when user is authenticated.
Here is my nginx myconfiguration.conf flie inside etc/nginx/sites-enabled/:
# Proxy Server to back-end site
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name internal.example.com;
# Internal web application
location / {
auth_request /aut;
error_page 401 = #error401;
proxy_pass http://192.168.1.13:8080;
}
# Autentication application
location = /aut {
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_pass http://192.168.1.130:8080/Autentication/Auth;
}
# Redirect to login site
location #error401 {
return 302 http://example.com/Autentication/login;
}
}
# Proxy server to Login site
server {
listen 80;
listen [::]:80;
server_name example.com;
# Internal web application for login
location / {
proxy_pass http://192.168.1.130:8080;
}
}
If users requests are authenticated through the auth_request /aut; everithing works great, but if we force the auth_request (on our auth api) to answer 'HTTP error 401' we slip into 2 different situations:
A) if the user refresh the page, everithing works: it means that the request do not pass the authorization and the client is redirected to our login page http://example.com/Autentication/login
B) if the user tries to fetch data from an api using javascript we receive this 3 errors in the browser console:
ERROR .1)
Access to XMLHttpRequest at 'http://example.com/Autentication'
(redirected from 'http://internal.example.com/TestServer/servlet')
from origin 'http://internal.example.com' has been blocked by CORS policy:
Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response
ERROR 2)
Access to XMLHttpRequest at 'http://example.com/Autentication'
(redirected from 'http://internal.example.com/page.html')
from origin 'http://internal.example.com/' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
ERROR 3)
Access to XMLHttpRequest at 'http://example.com/Autentication'
(redirected from 'http://internal.example.com/TestServer/servlets)
from origin 'http://internal.example.com' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
We tried, as suggested here, to add this configurations in our nginx myconfiguration.conf inside the location block but it didn't solved our problem:
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
}
After few days of testing some change here and there I SOLVED the problem:
No configuration needed on tomcat server (i mean no cors headers handled on tomcat server).
What i changed and was enough to let the whole infrastructure work was the myconfig.conf file on NGINX.
Here is the correct myconfig.conf:
# SERVER PROXY INTERNAL (can access only when auth_request is passed)----------------------------------------
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name internal.example.com;
# Proxy to internal tomcat with auth_request to /provaut
location / {
auth_request /prova_aut;
error_page 401 = #error401;
proxy_pass http://192.168.1.13:8080;
}
location = /prova_aut {
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_pass http://192.168.1.130:8080/Auth;
}
# Redirect to LOGIN
location #error401 {
return 302 http://example.com/Login;
}
}
# SERVER PROXY FOR LOGIN AND AUTH TOMCAT'S APP --------------------------
server {
listen 80;
listen [::]:80;
server_name example.com;
access_log /var/log/nginx/reverse-access.log;
error_log /var/log/nginx/reverse-error.log;
# Proxy to Authentication_app's tomcat
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'http://internal.example.com' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' 'http://internal.example.com' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range,Access-Control-Allow-Origin,Access-Control-Allow-Credentials' always;
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' 'http://internal.example.com' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range,Access-Control-Allow-Origin,Access-Control-Allow-Credentials' always;
}
proxy_pass http://192.168.1.130:8080;
}
}
What really made the trick was adding the two lines below in the /location block of the Login/Auth server
'Access-Control-Allow-Origin' 'http://internal.example.com' always;
and
'Access-Control-Allow-Credentials' 'true' always;
I Really hope this can help someone else ;)

Lit-html not found when using polymer build

I have a fairly basic lit-html app that works locally when it's not build.
However when I build it using polymer build using the following config:
{
"entrypoint": "index.html",
"shell": "src/school-home.js",
"sources": [
"src/**.js",
"package.json"
],
"extraDependencies": [
"node_modules/#webcomponents/webcomponentsjs/bundles/**"
],
"builds": [
{"preset": "es6-bundled"}
]
}
This results in a successful build but for some reason I keep getting an error:
I just don't get why it doesn't work. This like the basics of the basics yet it doesn't get found?
Aside: I use nginx for windows since I want to test E2E with my developed APIs.
An additional issue is that I keep getting CORS error for my API calls even though they are on the exact same location?!!
Please help.
Edit:
My NGINX config:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include cors-settings.conf;
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 8000;
server_name localhost;
location /school {
root /html/ing-school;
try_files $uri $uri/ $uri.html /index.html;
}
location ~ ^/(api|login|logout) {
proxy_pass http://localhost:8080;
proxy_set_header Connection "";
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested- With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content- Range';
}
}
location /ws {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}

rest api direct vs nginx proxy

I am a newbie in nginx and CORS and finding it challenging getting this right.
I have rest services hosted on a server which blocks CORS so installed nginx to proxy for rest call. What works:
rest api call (from angular code) to backend server after enabling CORS
rest api call (from chrome) to frontend nginx server which has cors enables
What doesn't work: rest api call (from angular code) to frontend nginx
I think the CORS part work as I do not see that error anymore but angular is getting a null response.
For above scenarios, I have tried using GET and POST methods. Response code is 200 OK even for failed scenario.
Here is the nginx conf:
upstream myserver {
server myserver.com:8443;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name myserver.com;
ssl_certificate /some.crt;
ssl_certificate_key /some.key;
location /rest-service/ {
# Simple requests
if ($request_method ~* "(GET|POST)") {
add_header "Access-Control-Allow-Origin" *;
}
# Preflighted requests
if ($request_method = OPTIONS ) {
add_header "Access-Control-Allow-Origin" *;
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
return 200;
}
proxy_pass_header Server;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_set_header X-NginX-Proxy true;
proxy_connect_timeout 5;
proxy_read_timeout 240;
proxy_intercept_errors on;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass https://myserver/rest-service/;
proxy_ssl_trusted_certificate /some.pem;
proxy_ssl_verify off;
proxy_ssl_session_reuse on;
}
}
Here is the angular/typescript code (running from loaclhost):
ngOnInit() {
let url='https://myserver.com/rest-service/login?login=admin&password=password';
this.http.get(this.url).subscribe((response) => {console.log(response); });
}
I think I figured out the issue and posting it here; hope it helps someone.
Following worked:
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'http://localhost:4200' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Origin,Keep-Alive,User-Agent,Cache-Control,Content-Type,Accept' always;
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ( $request_method = 'GET' ) {
add_header 'Access-Control-Allow-Origin' 'http://localhost:4200' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Origin,Keep-Alive,User-Agent,Cache-Control,Content-Type,Accept' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
if ( $request_method = 'POST' ) {
add_header 'Access-Control-Allow-Origin' 'http://localhost:4200' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Origin,Keep-Alive,User-Agent,Cache-Control,Content-Type,Accept' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}

NGINX + Vue HTML mode config giving 404

I have a Vue app running inside an nginx:alpine container with a custom nginx config to deal with browser navigation (Vue Router's html mode).
The problem is that any path other than the root (/) is giving 404's, with error messages like:
2018/11/25 07:56:13 [error] 7#7: *2 open() "/usr/share/nginx/html/home" failed (2: No such file or directory), client: 172.17.0.1, server: localhost, request: "GET /home HTTP/1.1", host: "localhost:4000"
I'm using a custom nginx config file that looks like this:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
}
location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
# Some basic cache-control for static files to be sent to the browser
expires max;
add_header Pragma public;
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
is there something wrong with my nginx.conf?
There are issues regarding using if inside a location block.
The try_files statement is not executed when the if ($request_method = 'GET') block is selected to process the request.
You can fix the problem by replacing the try_files statement with another if statement.
For example:
location / {
if (!-e $request_filename) { rewrite ^ /index.html last; }
if ($request_method = 'OPTIONS') { ... }
if ($request_method = 'POST') { ... }
if ($request_method = 'GET') { ... }
}

Resources