Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django CSRF problems with cookies disabled

Tags:

django

csrf

While testing an application I've written in Django, I've found that I'm be thrown a HTTP 403 Forbidden error every time I submit a form. I am aware that the CSRF middleware checks for a cookie with the CSRF token - but what should my approach be given a user that has cookies disabled?

Do I need to be checking whether the user has cookies enabled in each of my views or is there a more efficient approach?

Thanks in advance.

This question dealt with Django pre-1.2 -- the solution is different if you have an older version.

like image 600
Rubix Avatar asked Jun 01 '26 02:06

Rubix


2 Answers

Starting in Django 1.2 you can override the 403 response using CSRF_FAILURE_VIEW.

like image 187
Josh Tauberer Avatar answered Jun 03 '26 14:06

Josh Tauberer


Just for anyone who has the same problem: I found that the best suited solution for me was writing some middleware that displays a generic 403 error page:

from django.http import HttpResponseForbidden
from django.conf import settings

from django.template import RequestContext
from django.shortcuts import render_to_response

class PermissionErrorMiddleware(object):
    def process_response(self, request, response):
        if isinstance(response, HttpResponseForbidden):
            return render_to_response('403.html', context_instance=RequestContext(request)) 

        return response

It instructs the user that the most likely cause for the error page is that cookies are disabled (among other things), because my application doesn't really throw 403 errors otherwise. I have always preferred the "security through obscurity" approach, and throw 404 errors when a user shouldn't be accessing a particular page.

like image 43
Rubix Avatar answered Jun 03 '26 14:06

Rubix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!