Anurag Rana
Anurag Rana

Reputation: 1466

Different value of csrf token in response header and browser cookies. csrf verification failing in django 1.9

Most of the SO answers are asking to clear cookies and confirm middleware class. I have already tried that.

Python - 3.4
Django - 1.10
Using VirtualEnv.

I am getting Forbidden (403) CSRF verification failed. Request aborted. error on Django admin login screen. I have hosted my site on pythonanywhere.com with django version 1.9.

I have used exactly same code on different site where it is working perfectly fine.

Why there are different csrf-token values? What is the solution to this problem?

update 1: If I set debug = False in settings, it works fine. But I cant keep it as code is live.

update 2: Upon further investigation I found out that somehow browser cookie csrftoken's value is not being set to correct value which is being passed in response header. If I delete and the cookie from browser and then set it to correct value from console, post requests work.

update 3 : Now same issue is happening with every post request or form submission I am doing on my web app. CSRF token value sent in response header and source code is not same as the one being set in browser cookies.

update 4: Setting CSRF_COOKIE_NAME = "csrf_token" also didn't helped.

Upvotes: 5

Views: 4841

Answers (1)

Daniel Hepper
Daniel Hepper

Reputation: 29967

The unexpected value for the CSRF token is set when the browser tries to fetch the favicon.

The URL you have defined for your favicon seems to be invalid, and apparently, non-existing URLs are handled by your default view. This sets a different CSRF cookie, but the page that is displayed in the browser still has the initial CSRF token in the form.

Request loading the page: enter image description here

Request loading the favicon: enter image description here

You can fix this particular error by ensuring that the favicon exists.

Note this this bug will come back whenever any resource you link (e.g. an image) does not exist because your app renders the homepage instead of returning a 404 error.

Upvotes: 10

Related Questions