KP Root
KP Root

Reputation: 1

Why csrftoken cookie works?

I am upgrading from Django 1.4.3 to Django 11.3.

I have a web page with 2 different forms. Both forms are loaded with {%csrf_token%}. The flow is - the user logins in using form 1 ( ajax ) and then the second form is displayed. The user enters data in the second form and submits using ajax. Now, this request was failing if I did ( worked under Django 1.4.3 ) -

csrfmiddlewaretoken = $form.find('input[name="csrfmiddlewaretoken"]').val();

Now, to fix this I am getting csrftoken value from cookie and sending the cookie as part of ajax and it works -

csrfmiddlewaretoken = _getHelperCookie('csrftoken');

I am confused why getting the client cookie works? After login, Django calls rotate_token; what actually does this affect?

Upvotes: 0

Views: 183

Answers (1)

Alasdair
Alasdair

Reputation: 308819

As you say, Django rotates the CSRF token when you login as a security measure. This started in Django 1.5.2.

Since you have logged in with an ajax request, the old token is still in the html. When you fetch the token from the html, you are using the old token, so you get a CSRF error.

When you fetch the token from the cookie, you get the new token, so you avoid the error.

Upvotes: 1

Related Questions