Vas Vasanth
Vas Vasanth

Reputation: 159

Django, nginx and gunicorn csrf cookie not set

I have got a setup with nginx, gunicorn and Django, running on docker containers. Nginx is used as a reverse proxy. Everything works fine, but for POST methods I get the error saying Forbidden (CSRF cookie not set.). The same configuration works fine locally, but on production (ec2 on aws), this doesn't work.

Here is the nginx configuration:

upstream web {
  ip_hash;
  server web:8000;
}

server {

  location / {
      alias /src/frontend/dist/;
      try_files $uri $uri/ /index.html;
  }

  location /static {
    alias /src/static/;
    try_files $uri =404;
  }

  # works locally, but doesn't work in prodcution on ec2
  location /api/ {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://web; # pass to gunicorn

    # what to serve if upstream is not available or crashes
    # error_page 500 502 503 504 405 /error.html;
  }

  location @rewrites {
    rewrite ^(.+)$ /index.html last;
  }

  listen 80;
  server_name www.example.com;
}

I have checked the request headers and the cookie is not getting set. enter image description here

I have tried everything as suggest in SO. I have CsrfViewMiddleware set in the middlewares in Django settings. CSRF_COOKIE_SECURE & SESSION_COOKIE_SECURE are set to False. I have ran out of ideas and things to try. Please advice me on a solution.

Thanks

Versions:

Django==1.9.5
gunicorn==19.6.0
MySQL-python==1.2.5
nltk==3.3
pandas==0.23.3
django-pandas==0.5.1

NGINX=1.15.1

Upvotes: 1

Views: 1837

Answers (1)

Vas Vasanth
Vas Vasanth

Reputation: 159

This was an issue with auth. For CSRF cookie to be set, you need a session authenticated with a valid user. I created a super user within Django (for admin site), which now enables the cookies and we are able to post.

The reason why this was never picked up in the local dev environment is because it was using a cookie set from before. Once I cleared all cookies, I was able to recreate this issue locally as well.

Upvotes: 3

Related Questions