View decorators before CSRF verification?

41 views
Skip to first unread message

Dalton Hubble

unread,
Dec 15, 2013, 11:38:10 AM12/15/13
to django...@googlegroups.com
I have a function based view that should only respond to GET and HEAD requests so I used the @require_safe decorator.

@require_safe
def myview(request):
    # logic

so the expected response from a POST request is a 405 Response Not Allowed.

Using Postman to send a POST to the corresponding url, I actually get Forbidden 403, CSRF Verification Failed since the default     'django.middleware.csrf.CsrfViewMiddleware' is being used in MIDDLEWARE_CLASSES to protect all views. This must be happening because the CSRF middleware checks occur before view specific decorator function checks like @require_safe, @require_GET, etc.

Is this something to be bothered about? This is a request for advice and discussion rather than debugging a particular problem. I think I would prefer if there were a way for Django to check for view decorator compliance first because I think a 405 response is more descriptive and appropriate for the attempted action. 

However, if there were some middleware to check view decorators and that middleware class was ordered earlier than the CsrfViewMiddleware, caution would be needed - Django builtin view decorators seem safe, but user defined view decorators may allow POSTs without checking the csrftoken. Thoughts?

Simon Charette

unread,
Dec 15, 2013, 7:58:28 PM12/15/13
to django...@googlegroups.com
Hi Dalton,


> Is this something to be bothered about? This is a request for advice and discussion rather than debugging a particular problem. I think I would prefer if there were a way for Django to check for view decorator compliance first because I think a 405 response is more descriptive and appropriate for the attempted action.

IMO the whole require_http_methods family should be fixed to work with the CSRF machinery or at least it should be documented that when using those decorators and allowing *non-safe* methods you must exempt the decorated views from CSRF checks (@csrf_exempt).

Could you file a ticket to report this incompatibility?

Simon
Reply all
Reply to author
Forward
0 new messages