Django HTTP only CSRF cookie

Jan 19, 2017

Django sets a CSRF cookie to protect against cross site request forgeries. By default this cookie is set to be accessible to JavaScript on your web page. That means, the cookie will be accessible to a malicious script running on this page, too. Just to name a few things a malicious script could do in this situation:

  • Modify the cookie e.g. to prevent your users from submitting forms
  • Transmit it over the internet
  • Bypass the CSRF protection
  • Reuse it to send arbitrary requests to your server i.e. flood your system

The solution (in Django 1.6+) is to make your CSRF cookie HTTP only. Add this line to your settings.py file:

> CSRF_COOKIE_HTTPONLY = True

If you enable this and need to send the value of the CSRF token with Ajax requests, your JavaScript will need to pull the value from a hidden CSRF token form input on the page instead of from the cookie.