Ainda obtém dados mesmo que haja um problema de CORS no Nginx

Ainda obtém dados mesmo que haja um problema de CORS no Nginx

Estou tentando depurar um problema de CORS. Aqui está minha configuração que estou usandohttp://www.test-cors.org/para testar minhas regras Nginx. Recebo a mensagem abaixo no console do meu navegador quando o método que uso é OPTIONS. Mas ainda recebi os dados que são muito estranhos

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.

Recebo a mensagem abaixo se o método que uso for GET. Eu também recebo os dados

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.

Aqui está minha configuração atualizada do nginx, terceira atualização e coloquei em um novo arquivo.

  ❯ 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 ..."}';
     }
   }
  }

Eu comecei assim

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

machado ps | grep nginx mostra o processo

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 mostra a porta tcp associada ao meu nginx

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

O endereço IP está correto

 ❯ 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

Certifiquei-me de estar me conectando ao meu próprio servidor nginx em execução localmente usando curl

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

E os resultados ainda são os mesmos (capturas de tela das ferramentas de desenvolvimento do Chrome)https://i.stack.imgur.com/CB67D.jpg

Responder1

O problema é que você não está enviando cabeçalhos CORS no seu arquivo location /testcors.

Você só envia no serverbloco, para qualquer outro local.

A razão para isto é que add_headeras diretivas em blocos de nível inferiorsubstituir completamenteaqueles em blocos de nível superior. Então, como você usou add_headerno seu location, você também deve incluir todas as outras add_headerdiretivas novamente.

Para manter sua configuração SECA, você deve considerarfazendo um includearquivoadd_headerque contém as diretivas comuns e, em seguida include, em cada ponto relevante da configuração.

Responder2

UAU!!! Eu finalmente consegui que isso funcione!!! Aprendi que temos que dizer ao nginx o que queremos fazer se não corresponder à origem. Minha primeira impressão com o Nginx é que ele bloqueará automaticamente domínios se eles forem diferentes. 99% dos exemplos que encontrei não dizem isso.

# 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!";
   }
}

Aqui está test-cors.org falhando :)https://i.stack.imgur.com/3kKXY.png Anteriormente, ele era capaz de obter dados mesmo se houvesse erros de cors

informação relacionada