3

I have an api on api.mysite.com and the frontend on other.mysite.com and need AJAX to work, ideally with CSRF protection.

I can a csrftoken from an XHR, and it sets the cookie. When I make another XHR with withCredentials: true, that new XHR sends the csrftoken in the Cookie header.

But it seems the Django CsrfViewMiddleware only checks if the csrftoken is in the POST data, or in the x-csrftoken header. It does not check the cookie (if I'm not mistaken).

My problem is that there is no way the Javascript can read the csrftoken from the cookie, as it is a cookie from another site.

I see two solutions:

  • get an XHR to get a csrftoken in the body. That works when I land on the site, but the csrftoken can change (if I log out and in I believe)

  • have Django read the csrftoken from the cookie. This is what I would ideally achieve.

How would I make that work?

maxbellec
  • 16,093
  • 10
  • 36
  • 43
  • 1
    This seems to be a misunderstanding of CSRF protection. The whole point is to check the value in the POST against that in the cookie. – Daniel Roseman Sep 08 '16 at 15:08
  • This is what I was wondering after re-reading the Django docs. So the two tokens (one for the cookie, the other in the `csrfmiddlewaretoken` field) are supposed to be the same, is this what the middleware checks? So only solution #1 could work? – maxbellec Sep 08 '16 at 15:12

0 Answers0