14

How do I set HttpOnly cookie in Django?

And is it worth the effort to prevent XSS?

Daniel Holmes
  • 1,952
  • 2
  • 17
  • 28
Aviah Laor
  • 3,620
  • 2
  • 22
  • 27

3 Answers3

33

Use

SESSION_COOKIE_HTTPONLY = True

in settings.py

greg
  • 1,111
  • 14
  • 17
  • This is not part of Django 1.2 (tho it does work in the dev. version of 1.3) – bsk Jan 24 '11 at 22:19
  • It has been `True` by default since 1.4. – gregoltsov Oct 20 '14 at 12:44
  • 1
    Documented at: https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-SESSION_COOKIE_HTTPONLY – Jim Munro Aug 07 '17 at 18:33
  • OP asked how to set an HttpOnly cookie in django, not necessarily how to have django manage the session cookie specifically. https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.HttpResponse.set_cookie – kpup Jan 11 '21 at 21:28
7

In Django 3.0 you can set the following cookies to True in your settings.py:

For instances, if

SESSION_COOKIE_HTTPONLY = True

Then your client-side JavaScript will not be able to access the session cookie.

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
6
SESSION_COOKIE_PATH = '/;HttpOnly'

A discussion can be found here: http://groups.google.com/group/django-users/browse_thread/thread/bd7f562d5b938054/a229073ae836f4d2?lnk=raot&pli=1

miku
  • 181,842
  • 47
  • 306
  • 310
  • I tried the JavaScript:alert(document.cookie); command after doing the above changes and I still get a full cookie shown within the alert. I restarted Apache as well as truncated the django_session table. No difference. Am I doing something wrong? – Rok Jan 10 '11 at 20:18
  • @Rok: Did you log out and/or clear the existing session cookie? – James Socol Feb 25 '11 at 14:51
  • 4
    New in Django 1.4 CSRF_COOKIE_SECURE = True will also make the csrf cookie secure, and available over https-only. – Priyeshj Feb 02 '12 at 18:04