Django CSRF for both HTTP and HTTPS

2019-07-04 16:25发布

问题:

I have a blog that runs behind both HTTP and HTTPS and am running into issues with the csrf token verification.

The CSRF token is available in each form as it should be, but when I'm on the HTTP version of the site and try to commit a comment I get the following error.

Forbidden (403) CSRF verification failed. Request aborted.

Referer checking failed - http://mysite.com/blog/1/ does not match https://mysite.com/.

It works fine when viewing the blog via HTTPS.

Anyone know how to get the verification to match both?

回答1:

You might want to check your settings to see if you set the CSRF_COOKIE_SECURE parameter to True

This marks the cookie as secure and prevents the browser from accepting it over a non-secure connection, that is, HTTP.

To check whether thus is the source of the issue this you could use any view that works and drop in an assert False to get a debug screen and see whether the Csrf cookie is sent or nit.



回答2:

I figured it out. It was an issue with my fastcgi parameters

fastcgi_param HTTPS on;

setting an environ variable that required HTTPS to be on. Django does some extra enforcement for the csrf tokens when this variable is on.