Aún obtengo datos incluso si hay un problema de CORS en Nginx

Aún obtengo datos incluso si hay un problema de CORS en Nginx

Estoy intentando depurar un problema de CORS. Aquí está mi configuración que estoy usando.http://www.test-cors.org/para probar mis reglas de Nginx. Recibo el siguiente mensaje en la consola de mi navegador cuando el método que uso es OPCIONES. Pero aun así recibí los datos, lo cual es muy extraño.

Failed to load http://www.example.com:8009/testcors: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.test-cors.org' is therefore not allowed access.

Recibo el siguiente mensaje si el método que uso es GET. a mi tambien me salen los datos

Failed to load http://www.example.com:8009/testcors: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.test-cors.org' is therefore not allowed access.

Aquí está mi configuración de nginx actualizada, tercera actualización y la puse en un archivo nuevo.

  ❯ cat /usr/local/etc/nginx/nginx-mini.conf
  worker_processes  1;
  worker_rlimit_nofile 15000;

  error_log  logs/error.log;
  error_log  logs/error.log  notice;
  error_log  logs/error.log  info;

  events {
   worker_connections  5000;
   accept_mutex off;
  }


  http {
   include       mime.types;
   default_type  application/octet-stream;
   proxy_cookie_path / "/; HTTPOnly; Secure";

   types_hash_max_size 4096;
   access_log off;
   sendfile off;
   sendfile_max_chunk 512k;
   tcp_nopush      off;
   tcp_nodelay      on;
   output_buffers 1 3m;

   open_file_cache          max=10000 inactive=5m;
   open_file_cache_valid    2m;
   open_file_cache_min_uses 1;
   open_file_cache_errors   on;

   gzip on;
   gzip_disable "MSIE [1-6]\.(?!.*SV1)";
   gzip_http_version  1.1;
   gzip_comp_level    5;
   gzip_min_length    256;
   gzip_proxied       any;
   gzip_vary          on;

   gzip_types
     application/atom+xml
     application/javascript
     application/json
     application/rss+xml
     application/vnd.ms-fontobject
     application/x-font-ttf
     application/x-javascript
     application/x-web-app-manifest+json
     application/xhtml+xml
     application/xml
     application/xml+rss
     font/opentype
     image/svg+xml
     image/x-icon
     text/css
     text/javascript
     text/js
     text/plain
     text/x-component
     text/xml;

   # CORS
   map $http_origin $allow_origin {
     default "";
     ~example.com "$http_origin";
   }

   server {
     listen 8009;
     server_name www.example.com;
     access_log /var/log/nginx/access.log;
     error_log /var/log/nginx/error.log debug;

     location /testcors {
        if ($request_method = 'OPTIONS') {
           add_header 'Access-Control-Allow-Origin' $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' 60;
           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' $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' $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';
           add_header GETMETHOD accessed;
           add_header Content-Type "application/json; charset=utf-8";
        }

       add_header Content-Type "application/json; charset=utf-8";
       return 200 '{"code": 200, "reason": "Testing CORS ..."}';
     }
   }
  }

lo empecé de esta manera

sudo nginx -c /usr/local/etc/nginx/nginx-mini.conf

ps hacha | grep nginx muestra el proceso

31528   ??  Ss     0:00.00 nginx: master process nginx -c /usr/local/etc/nginx/nginx-mini.conf
31529   ??  S      0:00.00 nginx: worker process
31787 s003  R+     0:00.00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn nginx

netstat muestra el puerto tcp asociado con mi nginx

❯ netstat -na|grep 8009
tcp4       0      0  *.8009                 *.*                    LISTEN

La dirección IP es correcta.

 ❯ ping www.example.com
 PING airborne.gogoinflight.com (127.0.0.1): 56 data bytes
 64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.042 ms
 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.067 ms
 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.132 ms

Me aseguré de conectarme a mi propio servidor nginx que se ejecuta localmente usando curl

❯ curl http://www.example.com:8009/testcors
{"code": 200, "reason": "Testing CORS ..."}%

Y los resultados siguen siendo los mismos (capturas de pantalla de las herramientas de desarrollo de Chrome)https://i.stack.imgur.com/CB67D.jpg

Respuesta1

El problema es que no estás enviando encabezados CORS en tu location /testcors.

Solo los envías en el serverbloque, para cualquier otra ubicación.

La razón de esto es que add_headerlas directivas en bloques de nivel inferioranular completamenteaquellos en bloques de nivel superior. Entonces, debido a que ha usado add_headeren su location, también debe incluir todas las demás add_headerdirectivas nuevamente.

Para mantener su configuración SECO, debe considerarhaciendo un includearchivoque contiene las add_headerdirectivas comunes, y luego includeen cada punto relevante de la configuración.

Respuesta2

¡¡¡GUAUUOO!!! ¡¡¡Finalmente lo hice funcionar!!! Aprendí que tenemos que decirle a nginx lo que queremos hacer si no coincide con el origen. Mi primera impresión con Nginx es que bloqueará automáticamente los dominios si son diferentes. El 99% de los ejemplos que encontré no lo dice.

# CORS
map $http_origin $allow_origin {
  default "blocked";
  ~example.com "allowed";
}

map $allow_origin $origin_is_allowed {
  allowed $http_origin;
}

location ~ /getapi/?(?<capture>.*) {
   if ($allow_origin = 'allowed') {
      add_header 'Access-Control-Allow-Origin' "$origin_is_allowed";
      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';
      add_header Content-Type "application/json; charset=utf-8";
      proxy_pass http://localhost:7777/api/$capture;
   }
   if ($allow_origin = 'blocked') {
      add_header Content-Type "text/plain";
      return 403 "Your domain is not allowed!";
   }
}

Aquí está fallando test-cors.org :)https://i.stack.imgur.com/3kKXY.png Anteriormente podía obtener datos incluso si había errores de cors.

información relacionada