Thursday, November 13, 2014

csrf and request API

Notes to self on csrf protection in Django:

Django has built-in csrf protection if you use their decorators and form system.  In fact, by default you can't process a POST request without csrf protection.  Unfortunately, that protection acts as a wall against API POST requests not generated by the system.

The solution is simple: two views.  The view that you have to handle a GUI form needs the decorate.

A view that handles a curl or other programmatic request needs to be explicitly absolved of the decorator requirement.  Protection must come from authenticating each request instead of relying on a previous login--but that's not a hassle to an automated system.

from django.views.decorators.csrf import csrf_exempt, csrf_protect

@csrf_exempt
@csrf_protect

Any guess which view needs which decorator?

The form needs csrf protection because it is relying on a previous login.
The API authenticates every time and needs to be csrf_exempt.

No comments:

Post a Comment