Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Forcing CSRF token on all responses

My website has an AJAX POST view that can be called from any page on the app (event tracking). This view is protected by CSRF. In some cases, the CSRF cookie is not set, and the POST call fails.

Instead of manually decorating all views with @ensure_csrf_cookie, I'm thinking of writing I created a middleware that enforces Django to set the CSRF cookie on all responses. Is this approach correct? Does it create a security flaw I'm not aware of?

Update: here is the middleware code:

from django.middleware.csrf import get_token

class ForceCsrfCookieMiddleware(object):
    def process_request(self, request):
        get_token(request)
like image 316
Tzach Avatar asked Aug 26 '15 16:08

Tzach


1 Answers

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/

like image 136
tomas Avatar answered Oct 21 '22 12:10

tomas