tags:

views:

488

answers:

3

Hi there,

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.

A: 

If the form really must work without cookies, I think you just have to disable the CSRF middleware. You might be able to implement something similar using two form inputs where the value of one is random, and the other is a hash of the fist one and a secret.

Rasmus Kaj
I just figured it would be nice for the user to receive a notice that they do not have cookies enabled rather than an ugly 403 error.
Rubix
A: 

Did you try to pass csrf information as a hidden POST variable? In projects that I have been involved in it is usually done with a hidden input:

<input type="hidden" name="csrf" value="<?=$person->csrf?>" />

Sorry for PHP code, I don't remember how to do it in Django Templates.

Igor Zinov'yev
In Django, the variable is handled with a template tag. My concern was that the 403 error page being shown referenced the CSRF error and I couldn't customize it at all. I thought the best approach to solving that would be somehow checking for cookies before processing any views, but I have come up with a "make-do" solution.
Rubix
+1  A: 

Just to anyone who is having the same problem - I found that the solution that most suited me was to write some middleware for displaying 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 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.

Rubix