My objective is to restrict access to web application to any requests who don't have origin = http://localhost:3000
So after a bit a searching the internet I was able to come up (well, copy-paste) with this configuration:
location / {
set $cors '';
if ($http_origin ~ 'http://localhost:3000') {
set $cors 'true';
}
if ($cors = 'true') {
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, PATCH, DELETE, PATCH, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
}
if ($request_method = 'OPTIONS') {
# Tell client that this pre-flight info is valid for 20 days
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
proxy_pass http://10.131.20.142:8000/131j3yc1;
proxy_set_header received-from "nginx";
access_log /dev/stdout upstream_log;
}
And I tested it to see how it behaves. When I send a request with origin http://localhost:3000
it sends 200 OK with CORS headers. When I send request with no origin or different origin it still sends 200 OK but without the CORS headers. When browser get's the response with CORS header, it works fine but when CORS headers are not present, it throws an exception like this:
I am trying to understand what is this CORS configuration protecting here?
- The origins are plain headers - anyone can send any origin via nginx/curl
- Even when you send a wrong or no origin, you still get the data with 200
I am guessing either my config is wrong because it doesn't protect app against cross origin requests effectively OR my understanding of CORS is not correct.
Could someone help me figure what am I doing/understanding wrong here?