SignedForm: CSRF-protect forms with a hidden token field

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django import forms
from django.core.exceptions import PermissionDenied
from django.contrib.csrf.middleware import _make_token, _ERROR_MSG

class HiddenInputWithoutID(forms.HiddenInput):
    def render(self, name, value, attrs=None):
        if attrs and 'id' in attrs:
            del attrs['id']
        return super(HiddenInputWithoutID, self).render(name, value, attrs=attrs)

class SignedForm(forms.Form):
    csrf_token = forms.CharField(max_length=32, widget=HiddenInputWithoutID)

    def __init__(self, *args, **kwargs):
        request = kwargs.pop('request', None)
        if request:
            csrf_token = _make_token(request.session.session_key)
            kwargs.setdefault('initial', {})['csrf_token'] = csrf_token
        return super(SignedForm, self).__init__(*args, **kwargs)

    def clean_csrf_token(self):
        csrf_token = self.initial.get('csrf_token')
        value = self.cleaned_data.get('csrf_token')
        if csrf_token != value:
            raise PermissionDenied(_ERROR_MSG)
        return value

More like this

  1. Manual CSRF check for Django Facebook canvas applications by krvss 1 year, 8 months ago
  2. Add CSRF token to templates by coleifer 1 year, 10 months ago
  3. Django csrf_token Template Tag Fix by Reustle 2 years, 9 months ago
  4. Jquery ajax csrf framework for Django by chriszweber 1 year, 4 months ago
  5. Referer-checking view decorators by robbie 6 years, 1 month ago

Comments

Tarken (on December 10, 2008):

I'm curious, what is the advantage of using this over the Django contrib CSRF Middleware[1]?

[1] http://docs.djangoproject.com/en/dev/ref/contrib/csrf/

#

exogen (on October 17, 2009):

@Tarken: Greater control. See the Limitations section on that page. Also, I consider the approach of parsing and rewriting the entire response inherently ugly. :)

#

(Forgotten your password?)