[Fixed]-Django: Forcing CSRF token on all responses


No, there is no problem as long as you’re not rendering the csrf token inside a form that posts to an external site (but that would be a problem anyways, no matter where you implement it). You can set it on a middleware, or some views, or on all views, it doesn’t matter.

The CSRF protection is only made to ensure that the request is coming from your site. No matter how often you set the cookie, if the request includes the correct CSRF token it means that the request is indeed coming from your site, because only your site can access your cookies. (of course this only holds if you are not leaking the CSRF token to third parties, for example by sending it to other sites)

In few words, this is how it works:

  1. The server sets a cookie with a random value in the response
  2. Your site reads that value and sends it to the server when posting data
  3. Since cookies can only be accessed from the same domain that set them, there is no way for another site to read that cookie. Therefore, whenever you receive a request that has the right csrf token, you are assured that that request is coming from your site.

For a very good explanation of CSRF, have a look at this article: http://www.gnucitizen.org/blog/csrf-demystified/


Leave a comment