Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin - CSRF verification failed. Request aborted

Tags:

nginx

django

Whenever I try to login to Django's admin app, after filling in username and password and submitting the form, the page hangs forever.

When I refresh the POST request in the browser, I get:

CSRF verification failed. Request aborted.

enter image description here

When I refresh the page again, everything works, I see admin app, I am logged in and I can go and do CRUD operations on my apps and tables.

Any ideas why?

I have Nginx reverse proxy in front of the Django app doing https handshake. So when you go to (example):

https://platform.staging.com/admin/

Nginx reverse proxies that to

http://admin1.staging.platform.com/admin/

This is my nginx config:

upstream admin-cluster {
  ip_hash;
  server admin1.staging.platform.com;
}

# force redirect of http to https
# application will be available only over https
server {
  listen 80 default;
  server_name platform.staging.com;
  rewrite     ^ https://$server_name$request_uri? permanent;
}

# https server
# traffic is going to local web servers over normal http
# front nginx proxy server will hold ssl session
server {
  listen 443 ssl spdy;
  server_name platform.staging.com;
  keepalive_timeout 70;

  ssl                 on;
  ssl_certificate     /etc/ssl/platform.staging.com.crt;
  ssl_certificate_key /etc/ssl/platform.staging.com.key;

  location /admin {
    proxy_pass http://admin-cluster;
  }

}

EDIT:

So, I found a workaround. When I allow also port 80 on my Nginx reverse proxy but redirect all http requests to https like this:

server {
  listen 80 default;
  server_name platform.staging.com;
  rewrite     ^ https://$server_name$request_uri? permanent;
}

It fixed the problem. Any idea why?

like image 808
Richard Knop Avatar asked Jan 15 '14 10:01

Richard Knop


1 Answers

Check your settings for values overriding the SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE values, as the problem could be related to the CSRF cookie. EDIT: I have in fact these two values set to True.

Also, check your SECURE_PROXY_SSL_HEADER setting, although I'm not sure it has relation with your problem. I am missing a proxy_set_header X-Forwarded-Protocol directive in your nginx conf file used for letting Django know that you are passing through a proxy.

like image 153
Alfredo Láinez Avatar answered Oct 30 '22 17:10

Alfredo Láinez