Release 0.2.2 does not exempt POST requests from CSRF validation in Django 1.2 and later

Issue #82 open
Brian Zambrano
created an issue

Django's new CSRF protection appears to be much more strict. If using django.middleware.csrf.CsrfViewMiddleware, any POST must contain a valid csrf_token. Furthermore, if you use django.contrib.auth.views.login, you now have to use this middleware.

The effect of this is that any POST sent to piston fails the csrf check.

It's possible to bypass this check by adding a decorator to your views, but that doesn't work for instances of piston.Resource. A simple solution is to mimic Django's decorator by setting an attribute in the piston.Resource constructor:

{{{ self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True) }}}

There very well may be a better way to handle this, but this solution works. Note this is using rev 11682 of django trunk.

Comments (29)

  1. Jesper Noehr repo owner
    • changed status to open

    I don't test against trunk, to be honest, but your solution seems to be what I would've done.

    CSRF doesn't make much sense for an API, especially not one running OAuth, since the token must be revealed to the client prior to the request.

    I suppose it's possible to simulate an API request via ones browser ($.ajax("/malicious_stuff/"), et. al), but CSRF is not the answer here.

    If you provide a patch with your proposed solution, I'll gladly import it. Make sure you use your real name when doing the commit/patch so I can add you to AUTHORS.txt.

  2. Brian Zambrano reporter

    Yeah, I agree that CSRF doesn't make sense at all for an API. Here is how I hit this issue:

    • I use django.contrib.auth.view.login for the website
    • The above enforces using CsrfViewMiddleware
    • CsrfViewMiddleware enforces a csrf token to be present is all POST request
    • Calls to create methods in piston fail

    Attached is an export from a fork I made...hopefully I did this right since it's my first submitting anything here.


  3. aroy

    Just tested the patch against trunk. A simple test POST request with curl worked with the patch, whereas before I was getting the CSRF info page as my response.

    @Anonymous: I don't think the patch will do anything in your case. 1.04 didn't have CSRF exceptions yet. You'd have to manually bypass CSRFViewMiddleware's CSRF token-checking (which is what @csrf_exempt does).

  4. Anonymous

    I'm hitting this on Debian Squeeze.


    • Django is 1.2.1 (debian version 1.2.1-1)
    • piston is 0.2.2 (debian version 0.2.2.-1)
  5. Log in to comment