开发者

Django CSRF problems with cookies disabled

开发者 https://www.devze.com 2022-12-12 14:39 出处:网络
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 wit

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 to开发者_如何学Pythonken - 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.


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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消