Search code examples
javascriptcookiesnginxcorstornado

Tornado + nginx CORS cookies


I have Tornado app, working as an API server, that processes requests from several other sites. I also plan to use nginx as load balancer.

The problem is CORS cookies. When someone is visiting partner site, partner.com, for example, JS script from there sends several requests to my server. The first request is aimed to set several cookies. But it doesnt.

What i have:

  1. No header settings on tornado
  2. The following config on nginx

    access_log /var/log/nginx/api_access.log;
    error_log /var/log/nginx/api_error.log;
    
    add_header Access-Control-Allow-Origin http://salesmarine.ru;
    add_header Access-Control-Allow-Credentials 'true';
    add_header Set-Cookie test=111;
    
    location / {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_pass http://api;
        proxy_next_upstream error;
    }
    
  3. All requests from JS are sent with .withCredentials=true; option Here are the request data:

    Accept:*/*
    Accept-Encoding:gzip,deflate,sdch
    Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
    Cache-Control:max-age=0
    Connection:keep-alive
    Content-Type:application/x-www-form-urlencoded
    Cookie:t_id=d9ed7601a2074e78b5ba38ab58ad7043; t_id_session=0c7910f9b3194e899d233e68380df59f;                 test=111
    Host:server.com
    If-None-Match:"bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f"
    Origin:http://example.com
    Referer:http://example.com/test
    User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko)         Chrome/37.0.2062.120 Safari/537.36
    Query String Parametersview sourceview URL encoded
    id:54129700102392342dff6dbe
    apiKey:2a8bb0a06bca4ad59c4d4079dce30a30
    client_id:54129700102392342dff6dbe
    apikey:2a8bb0a06bca4ad59c4d4079dce30a30
    user_id:null
    Response Headersview source
    Access-Control-Allow-Credentials:true
    Access-Control-Allow-Origin:http://example.com
    Connection:keep-alive
    Date:Fri, 12 Sep 2014 19:40:17 GMT
    Etag:"bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f"
    Mime-Type:text/javascript
    Server:TornadoServer/4.0.2
    Set-Cookie:test=111
    

And no cookies are sent. What could be the problem?

And also what is better — control headers from tornado, or nginx?


Solution

  • Well, i've figured it out. The problem was CORS itself — i'm unable to set cookies for another domain. Access-Control-Allow-Credentials allow to do this, but that cookies would be unavailable for JS on that domain.

    There are plenty of links to this resourse, but it's really useful for understanding CORS.

    The second part of my initial question is stay ambiguous to me. A wild guess — if you use nginx + tornado, nginx receives incoming requests first. So it should return proper headers.