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)