sessions.txt 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. ===================
  2. How to use sessions
  3. ===================
  4. .. module:: django.contrib.sessions
  5. :synopsis: Provides session management for Django projects.
  6. Django provides full support for anonymous sessions. The session framework
  7. lets you store and retrieve arbitrary data on a per-site-visitor basis. It
  8. stores data on the server side and abstracts the sending and receiving of
  9. cookies. Cookies contain a session ID -- not the data itself (unless you're
  10. using the :ref:`cookie based backend<cookie-session-backend>`).
  11. Enabling sessions
  12. =================
  13. Sessions are implemented via a piece of :doc:`middleware </ref/middleware>`.
  14. To enable session functionality, do the following:
  15. * Edit the :setting:`MIDDLEWARE` setting and make sure it contains
  16. ``'django.contrib.sessions.middleware.SessionMiddleware'``. The default
  17. ``settings.py`` created by ``django-admin startproject`` has
  18. ``SessionMiddleware`` activated.
  19. If you don't want to use sessions, you might as well remove the
  20. ``SessionMiddleware`` line from :setting:`MIDDLEWARE` and
  21. ``'django.contrib.sessions'`` from your :setting:`INSTALLED_APPS`.
  22. It'll save you a small bit of overhead.
  23. .. _configuring-sessions:
  24. Configuring the session engine
  25. ==============================
  26. By default, Django stores sessions in your database (using the model
  27. ``django.contrib.sessions.models.Session``). Though this is convenient, in
  28. some setups it's faster to store session data elsewhere, so Django can be
  29. configured to store session data on your filesystem or in your cache.
  30. Using database-backed sessions
  31. ------------------------------
  32. If you want to use a database-backed session, you need to add
  33. ``'django.contrib.sessions'`` to your :setting:`INSTALLED_APPS` setting.
  34. Once you have configured your installation, run ``manage.py migrate``
  35. to install the single database table that stores session data.
  36. .. _cached-sessions-backend:
  37. Using cached sessions
  38. ---------------------
  39. For better performance, you may want to use a cache-based session backend.
  40. To store session data using Django's cache system, you'll first need to make
  41. sure you've configured your cache; see the :doc:`cache documentation
  42. </topics/cache>` for details.
  43. .. warning::
  44. You should only use cache-based sessions if you're using the Memcached
  45. cache backend. The local-memory cache backend doesn't retain data long
  46. enough to be a good choice, and it'll be faster to use file or database
  47. sessions directly instead of sending everything through the file or
  48. database cache backends. Additionally, the local-memory cache backend is
  49. NOT multi-process safe, therefore probably not a good choice for production
  50. environments.
  51. If you have multiple caches defined in :setting:`CACHES`, Django will use the
  52. default cache. To use another cache, set :setting:`SESSION_CACHE_ALIAS` to the
  53. name of that cache.
  54. Once your cache is configured, you've got two choices for how to store data in
  55. the cache:
  56. * Set :setting:`SESSION_ENGINE` to
  57. ``"django.contrib.sessions.backends.cache"`` for a simple caching session
  58. store. Session data will be stored directly in your cache. However, session
  59. data may not be persistent: cached data can be evicted if the cache fills
  60. up or if the cache server is restarted.
  61. * For persistent, cached data, set :setting:`SESSION_ENGINE` to
  62. ``"django.contrib.sessions.backends.cached_db"``. This uses a
  63. write-through cache -- every write to the cache will also be written to
  64. the database. Session reads only use the database if the data is not
  65. already in the cache.
  66. Both session stores are quite fast, but the simple cache is faster because it
  67. disregards persistence. In most cases, the ``cached_db`` backend will be fast
  68. enough, but if you need that last bit of performance, and are willing to let
  69. session data be expunged from time to time, the ``cache`` backend is for you.
  70. If you use the ``cached_db`` session backend, you also need to follow the
  71. configuration instructions for the `using database-backed sessions`_.
  72. Using file-based sessions
  73. -------------------------
  74. To use file-based sessions, set the :setting:`SESSION_ENGINE` setting to
  75. ``"django.contrib.sessions.backends.file"``.
  76. You might also want to set the :setting:`SESSION_FILE_PATH` setting (which
  77. defaults to output from ``tempfile.gettempdir()``, most likely ``/tmp``) to
  78. control where Django stores session files. Be sure to check that your web
  79. server has permissions to read and write to this location.
  80. .. _cookie-session-backend:
  81. Using cookie-based sessions
  82. ---------------------------
  83. To use cookies-based sessions, set the :setting:`SESSION_ENGINE` setting to
  84. ``"django.contrib.sessions.backends.signed_cookies"``. The session data will be
  85. stored using Django's tools for :doc:`cryptographic signing </topics/signing>`
  86. and the :setting:`SECRET_KEY` setting.
  87. .. note::
  88. It's recommended to leave the :setting:`SESSION_COOKIE_HTTPONLY` setting
  89. on ``True`` to prevent access to the stored data from JavaScript.
  90. .. warning::
  91. **If the SECRET_KEY is not kept secret and you are using the**
  92. ``django.contrib.sessions.serializers.PickleSerializer``, **this can
  93. lead to arbitrary remote code execution.**
  94. An attacker in possession of the :setting:`SECRET_KEY` can not only
  95. generate falsified session data, which your site will trust, but also
  96. remotely execute arbitrary code, as the data is serialized using pickle.
  97. If you use cookie-based sessions, pay extra care that your secret key is
  98. always kept completely secret, for any system which might be remotely
  99. accessible.
  100. **The session data is signed but not encrypted**
  101. When using the cookies backend the session data can be read by the client.
  102. A MAC (Message Authentication Code) is used to protect the data against
  103. changes by the client, so that the session data will be invalidated when being
  104. tampered with. The same invalidation happens if the client storing the
  105. cookie (e.g. your user's browser) can't store all of the session cookie and
  106. drops data. Even though Django compresses the data, it's still entirely
  107. possible to exceed the :rfc:`common limit of 4096 bytes <2965#section-5.3>`
  108. per cookie.
  109. **No freshness guarantee**
  110. Note also that while the MAC can guarantee the authenticity of the data
  111. (that it was generated by your site, and not someone else), and the
  112. integrity of the data (that it is all there and correct), it cannot
  113. guarantee freshness i.e. that you are being sent back the last thing you
  114. sent to the client. This means that for some uses of session data, the
  115. cookie backend might open you up to `replay attacks`_. Unlike other session
  116. backends which keep a server-side record of each session and invalidate it
  117. when a user logs out, cookie-based sessions are not invalidated when a user
  118. logs out. Thus if an attacker steals a user's cookie, they can use that
  119. cookie to login as that user even if the user logs out. Cookies will only
  120. be detected as 'stale' if they are older than your
  121. :setting:`SESSION_COOKIE_AGE`.
  122. **Performance**
  123. Finally, the size of a cookie can have an impact on the speed of your site.
  124. .. _`replay attacks`: https://en.wikipedia.org/wiki/Replay_attack
  125. Using sessions in views
  126. =======================
  127. When ``SessionMiddleware`` is activated, each :class:`~django.http.HttpRequest`
  128. object -- the first argument to any Django view function -- will have a
  129. ``session`` attribute, which is a dictionary-like object.
  130. You can read it and write to ``request.session`` at any point in your view.
  131. You can edit it multiple times.
  132. .. class:: backends.base.SessionBase
  133. This is the base class for all session objects. It has the following
  134. standard dictionary methods:
  135. .. method:: __getitem__(key)
  136. Example: ``fav_color = request.session['fav_color']``
  137. .. method:: __setitem__(key, value)
  138. Example: ``request.session['fav_color'] = 'blue'``
  139. .. method:: __delitem__(key)
  140. Example: ``del request.session['fav_color']``. This raises ``KeyError``
  141. if the given ``key`` isn't already in the session.
  142. .. method:: __contains__(key)
  143. Example: ``'fav_color' in request.session``
  144. .. method:: get(key, default=None)
  145. Example: ``fav_color = request.session.get('fav_color', 'red')``
  146. .. method:: pop(key, default=__not_given)
  147. Example: ``fav_color = request.session.pop('fav_color', 'blue')``
  148. .. method:: keys()
  149. .. method:: items()
  150. .. method:: setdefault()
  151. .. method:: clear()
  152. It also has these methods:
  153. .. method:: flush()
  154. Deletes the current session data from the session and deletes the session
  155. cookie. This is used if you want to ensure that the previous session data
  156. can't be accessed again from the user's browser (for example, the
  157. :func:`django.contrib.auth.logout()` function calls it).
  158. .. method:: set_test_cookie()
  159. Sets a test cookie to determine whether the user's browser supports
  160. cookies. Due to the way cookies work, you won't be able to test this
  161. until the user's next page request. See `Setting test cookies`_ below for
  162. more information.
  163. .. method:: test_cookie_worked()
  164. Returns either ``True`` or ``False``, depending on whether the user's
  165. browser accepted the test cookie. Due to the way cookies work, you'll
  166. have to call ``set_test_cookie()`` on a previous, separate page request.
  167. See `Setting test cookies`_ below for more information.
  168. .. method:: delete_test_cookie()
  169. Deletes the test cookie. Use this to clean up after yourself.
  170. .. method:: get_session_cookie_age()
  171. Returns the age of session cookies, in seconds. Defaults to
  172. :setting:`SESSION_COOKIE_AGE`.
  173. .. method:: set_expiry(value)
  174. Sets the expiration time for the session. You can pass a number of
  175. different values:
  176. * If ``value`` is an integer, the session will expire after that
  177. many seconds of inactivity. For example, calling
  178. ``request.session.set_expiry(300)`` would make the session expire
  179. in 5 minutes.
  180. * If ``value`` is a ``datetime`` or ``timedelta`` object, the session
  181. will expire at that specific date/time.
  182. * If ``value`` is ``0``, the user's session cookie will expire
  183. when the user's web browser is closed.
  184. * If ``value`` is ``None``, the session reverts to using the global
  185. session expiry policy.
  186. Reading a session is not considered activity for expiration
  187. purposes. Session expiration is computed from the last time the
  188. session was *modified*.
  189. .. method:: get_expiry_age()
  190. Returns the number of seconds until this session expires. For sessions
  191. with no custom expiration (or those set to expire at browser close), this
  192. will equal :setting:`SESSION_COOKIE_AGE`.
  193. This function accepts two optional keyword arguments:
  194. - ``modification``: last modification of the session, as a
  195. :class:`~datetime.datetime` object. Defaults to the current time.
  196. - ``expiry``: expiry information for the session, as a
  197. :class:`~datetime.datetime` object, an :class:`int` (in seconds), or
  198. ``None``. Defaults to the value stored in the session by
  199. :meth:`set_expiry`, if there is one, or ``None``.
  200. .. method:: get_expiry_date()
  201. Returns the date this session will expire. For sessions with no custom
  202. expiration (or those set to expire at browser close), this will equal the
  203. date :setting:`SESSION_COOKIE_AGE` seconds from now.
  204. This function accepts the same keyword arguments as :meth:`get_expiry_age`.
  205. .. method:: get_expire_at_browser_close()
  206. Returns either ``True`` or ``False``, depending on whether the user's
  207. session cookie will expire when the user's web browser is closed.
  208. .. method:: clear_expired()
  209. Removes expired sessions from the session store. This class method is
  210. called by :djadmin:`clearsessions`.
  211. .. method:: cycle_key()
  212. Creates a new session key while retaining the current session data.
  213. :func:`django.contrib.auth.login()` calls this method to mitigate against
  214. session fixation.
  215. .. _session_serialization:
  216. Session serialization
  217. ---------------------
  218. By default, Django serializes session data using JSON. You can use the
  219. :setting:`SESSION_SERIALIZER` setting to customize the session serialization
  220. format. Even with the caveats described in :ref:`custom-serializers`, we highly
  221. recommend sticking with JSON serialization *especially if you are using the
  222. cookie backend*.
  223. For example, here's an attack scenario if you use :mod:`pickle` to serialize
  224. session data. If you're using the :ref:`signed cookie session backend
  225. <cookie-session-backend>` and :setting:`SECRET_KEY` is known by an attacker
  226. (there isn't an inherent vulnerability in Django that would cause it to leak),
  227. the attacker could insert a string into their session which, when unpickled,
  228. executes arbitrary code on the server. The technique for doing so is simple and
  229. easily available on the internet. Although the cookie session storage signs the
  230. cookie-stored data to prevent tampering, a :setting:`SECRET_KEY` leak
  231. immediately escalates to a remote code execution vulnerability.
  232. Bundled serializers
  233. ~~~~~~~~~~~~~~~~~~~
  234. .. class:: serializers.JSONSerializer
  235. A wrapper around the JSON serializer from :mod:`django.core.signing`. Can
  236. only serialize basic data types.
  237. In addition, as JSON supports only string keys, note that using non-string
  238. keys in ``request.session`` won't work as expected::
  239. >>> # initial assignment
  240. >>> request.session[0] = 'bar'
  241. >>> # subsequent requests following serialization & deserialization
  242. >>> # of session data
  243. >>> request.session[0] # KeyError
  244. >>> request.session['0']
  245. 'bar'
  246. Similarly, data that can't be encoded in JSON, such as non-UTF8 bytes like
  247. ``'\xd9'`` (which raises :exc:`UnicodeDecodeError`), can't be stored.
  248. See the :ref:`custom-serializers` section for more details on limitations
  249. of JSON serialization.
  250. .. class:: serializers.PickleSerializer
  251. Supports arbitrary Python objects, but, as described above, can lead to a
  252. remote code execution vulnerability if :setting:`SECRET_KEY` becomes known
  253. by an attacker.
  254. .. deprecated:: 4.1
  255. Due to the risk of remote code execution, this serializer is deprecated
  256. and will be removed in Django 5.0.
  257. .. _custom-serializers:
  258. Write your own serializer
  259. ~~~~~~~~~~~~~~~~~~~~~~~~~
  260. Note that the :class:`~django.contrib.sessions.serializers.JSONSerializer`
  261. cannot handle arbitrary Python data types. As is often the case, there is a
  262. trade-off between convenience and security. If you wish to store more advanced
  263. data types including ``datetime`` and ``Decimal`` in JSON backed sessions, you
  264. will need to write a custom serializer (or convert such values to a JSON
  265. serializable object before storing them in ``request.session``). While
  266. serializing these values is often straightforward
  267. (:class:`~django.core.serializers.json.DjangoJSONEncoder` may be helpful),
  268. writing a decoder that can reliably get back the same thing that you put in is
  269. more fragile. For example, you run the risk of returning a ``datetime`` that
  270. was actually a string that just happened to be in the same format chosen for
  271. ``datetime``\s).
  272. Your serializer class must implement two methods,
  273. ``dumps(self, obj)`` and ``loads(self, data)``, to serialize and deserialize
  274. the dictionary of session data, respectively.
  275. Session object guidelines
  276. -------------------------
  277. * Use normal Python strings as dictionary keys on ``request.session``. This
  278. is more of a convention than a hard-and-fast rule.
  279. * Session dictionary keys that begin with an underscore are reserved for
  280. internal use by Django.
  281. * Don't override ``request.session`` with a new object, and don't access or
  282. set its attributes. Use it like a Python dictionary.
  283. Examples
  284. --------
  285. This simplistic view sets a ``has_commented`` variable to ``True`` after a user
  286. posts a comment. It doesn't let a user post a comment more than once::
  287. def post_comment(request, new_comment):
  288. if request.session.get('has_commented', False):
  289. return HttpResponse("You've already commented.")
  290. c = comments.Comment(comment=new_comment)
  291. c.save()
  292. request.session['has_commented'] = True
  293. return HttpResponse('Thanks for your comment!')
  294. This simplistic view logs in a "member" of the site::
  295. def login(request):
  296. m = Member.objects.get(username=request.POST['username'])
  297. if m.check_password(request.POST['password']):
  298. request.session['member_id'] = m.id
  299. return HttpResponse("You're logged in.")
  300. else:
  301. return HttpResponse("Your username and password didn't match.")
  302. ...And this one logs a member out, according to ``login()`` above::
  303. def logout(request):
  304. try:
  305. del request.session['member_id']
  306. except KeyError:
  307. pass
  308. return HttpResponse("You're logged out.")
  309. The standard :meth:`django.contrib.auth.logout` function actually does a bit
  310. more than this to prevent inadvertent data leakage. It calls the
  311. :meth:`~backends.base.SessionBase.flush` method of ``request.session``.
  312. We are using this example as a demonstration of how to work with session
  313. objects, not as a full ``logout()`` implementation.
  314. Setting test cookies
  315. ====================
  316. As a convenience, Django provides a way to test whether the user's browser
  317. accepts cookies. Call the :meth:`~backends.base.SessionBase.set_test_cookie`
  318. method of ``request.session`` in a view, and call
  319. :meth:`~backends.base.SessionBase.test_cookie_worked` in a subsequent view --
  320. not in the same view call.
  321. This awkward split between ``set_test_cookie()`` and ``test_cookie_worked()``
  322. is necessary due to the way cookies work. When you set a cookie, you can't
  323. actually tell whether a browser accepted it until the browser's next request.
  324. It's good practice to use
  325. :meth:`~backends.base.SessionBase.delete_test_cookie()` to clean up after
  326. yourself. Do this after you've verified that the test cookie worked.
  327. Here's a typical usage example::
  328. from django.http import HttpResponse
  329. from django.shortcuts import render
  330. def login(request):
  331. if request.method == 'POST':
  332. if request.session.test_cookie_worked():
  333. request.session.delete_test_cookie()
  334. return HttpResponse("You're logged in.")
  335. else:
  336. return HttpResponse("Please enable cookies and try again.")
  337. request.session.set_test_cookie()
  338. return render(request, 'foo/login_form.html')
  339. Using sessions out of views
  340. ===========================
  341. .. note::
  342. The examples in this section import the ``SessionStore`` object directly
  343. from the ``django.contrib.sessions.backends.db`` backend. In your own code,
  344. you should consider importing ``SessionStore`` from the session engine
  345. designated by :setting:`SESSION_ENGINE`, as below:
  346. >>> from importlib import import_module
  347. >>> from django.conf import settings
  348. >>> SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
  349. An API is available to manipulate session data outside of a view::
  350. >>> from django.contrib.sessions.backends.db import SessionStore
  351. >>> s = SessionStore()
  352. >>> # stored as seconds since epoch since datetimes are not serializable in JSON.
  353. >>> s['last_login'] = 1376587691
  354. >>> s.create()
  355. >>> s.session_key
  356. '2b1189a188b44ad18c35e113ac6ceead'
  357. >>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
  358. >>> s['last_login']
  359. 1376587691
  360. ``SessionStore.create()`` is designed to create a new session (i.e. one not
  361. loaded from the session store and with ``session_key=None``). ``save()`` is
  362. designed to save an existing session (i.e. one loaded from the session store).
  363. Calling ``save()`` on a new session may also work but has a small chance of
  364. generating a ``session_key`` that collides with an existing one. ``create()``
  365. calls ``save()`` and loops until an unused ``session_key`` is generated.
  366. If you're using the ``django.contrib.sessions.backends.db`` backend, each
  367. session is a normal Django model. The ``Session`` model is defined in
  368. ``django/contrib/sessions/models.py``. Because it's a normal model, you can
  369. access sessions using the normal Django database API::
  370. >>> from django.contrib.sessions.models import Session
  371. >>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
  372. >>> s.expire_date
  373. datetime.datetime(2005, 8, 20, 13, 35, 12)
  374. Note that you'll need to call
  375. :meth:`~base_session.AbstractBaseSession.get_decoded()` to get the session
  376. dictionary. This is necessary because the dictionary is stored in an encoded
  377. format::
  378. >>> s.session_data
  379. 'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
  380. >>> s.get_decoded()
  381. {'user_id': 42}
  382. When sessions are saved
  383. =======================
  384. By default, Django only saves to the session database when the session has been
  385. modified -- that is if any of its dictionary values have been assigned or
  386. deleted::
  387. # Session is modified.
  388. request.session['foo'] = 'bar'
  389. # Session is modified.
  390. del request.session['foo']
  391. # Session is modified.
  392. request.session['foo'] = {}
  393. # Gotcha: Session is NOT modified, because this alters
  394. # request.session['foo'] instead of request.session.
  395. request.session['foo']['bar'] = 'baz'
  396. In the last case of the above example, we can tell the session object
  397. explicitly that it has been modified by setting the ``modified`` attribute on
  398. the session object::
  399. request.session.modified = True
  400. To change this default behavior, set the :setting:`SESSION_SAVE_EVERY_REQUEST`
  401. setting to ``True``. When set to ``True``, Django will save the session to the
  402. database on every single request.
  403. Note that the session cookie is only sent when a session has been created or
  404. modified. If :setting:`SESSION_SAVE_EVERY_REQUEST` is ``True``, the session
  405. cookie will be sent on every request.
  406. Similarly, the ``expires`` part of a session cookie is updated each time the
  407. session cookie is sent.
  408. The session is not saved if the response's status code is 500.
  409. .. _browser-length-vs-persistent-sessions:
  410. Browser-length sessions vs. persistent sessions
  411. ===============================================
  412. You can control whether the session framework uses browser-length sessions vs.
  413. persistent sessions with the :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`
  414. setting.
  415. By default, :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``False``,
  416. which means session cookies will be stored in users' browsers for as long as
  417. :setting:`SESSION_COOKIE_AGE`. Use this if you don't want people to have to
  418. log in every time they open a browser.
  419. If :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``True``, Django will
  420. use browser-length cookies -- cookies that expire as soon as the user closes
  421. their browser. Use this if you want people to have to log in every time they
  422. open a browser.
  423. This setting is a global default and can be overwritten at a per-session level
  424. by explicitly calling the :meth:`~backends.base.SessionBase.set_expiry` method
  425. of ``request.session`` as described above in `using sessions in views`_.
  426. .. note::
  427. Some browsers (Chrome, for example) provide settings that allow users to
  428. continue browsing sessions after closing and re-opening the browser. In
  429. some cases, this can interfere with the
  430. :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` setting and prevent sessions
  431. from expiring on browser close. Please be aware of this while testing
  432. Django applications which have the
  433. :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` setting enabled.
  434. .. _clearing-the-session-store:
  435. Clearing the session store
  436. ==========================
  437. As users create new sessions on your website, session data can accumulate in
  438. your session store. If you're using the database backend, the
  439. ``django_session`` database table will grow. If you're using the file backend,
  440. your temporary directory will contain an increasing number of files.
  441. To understand this problem, consider what happens with the database backend.
  442. When a user logs in, Django adds a row to the ``django_session`` database
  443. table. Django updates this row each time the session data changes. If the user
  444. logs out manually, Django deletes the row. But if the user does *not* log out,
  445. the row never gets deleted. A similar process happens with the file backend.
  446. Django does *not* provide automatic purging of expired sessions. Therefore,
  447. it's your job to purge expired sessions on a regular basis. Django provides a
  448. clean-up management command for this purpose: :djadmin:`clearsessions`. It's
  449. recommended to call this command on a regular basis, for example as a daily
  450. cron job.
  451. Note that the cache backend isn't vulnerable to this problem, because caches
  452. automatically delete stale data. Neither is the cookie backend, because the
  453. session data is stored by the users' browsers.
  454. Settings
  455. ========
  456. A few :ref:`Django settings <settings-sessions>` give you control over session
  457. behavior:
  458. * :setting:`SESSION_CACHE_ALIAS`
  459. * :setting:`SESSION_COOKIE_AGE`
  460. * :setting:`SESSION_COOKIE_DOMAIN`
  461. * :setting:`SESSION_COOKIE_HTTPONLY`
  462. * :setting:`SESSION_COOKIE_NAME`
  463. * :setting:`SESSION_COOKIE_PATH`
  464. * :setting:`SESSION_COOKIE_SAMESITE`
  465. * :setting:`SESSION_COOKIE_SECURE`
  466. * :setting:`SESSION_ENGINE`
  467. * :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`
  468. * :setting:`SESSION_FILE_PATH`
  469. * :setting:`SESSION_SAVE_EVERY_REQUEST`
  470. * :setting:`SESSION_SERIALIZER`
  471. .. _topics-session-security:
  472. Session security
  473. ================
  474. Subdomains within a site are able to set cookies on the client for the whole
  475. domain. This makes session fixation possible if cookies are permitted from
  476. subdomains not controlled by trusted users.
  477. For example, an attacker could log into ``good.example.com`` and get a valid
  478. session for their account. If the attacker has control over ``bad.example.com``,
  479. they can use it to send their session key to you since a subdomain is permitted
  480. to set cookies on ``*.example.com``. When you visit ``good.example.com``,
  481. you'll be logged in as the attacker and might inadvertently enter your
  482. sensitive personal data (e.g. credit card info) into the attacker's account.
  483. Another possible attack would be if ``good.example.com`` sets its
  484. :setting:`SESSION_COOKIE_DOMAIN` to ``"example.com"`` which would cause
  485. session cookies from that site to be sent to ``bad.example.com``.
  486. Technical details
  487. =================
  488. * The session dictionary accepts any :mod:`json` serializable value when using
  489. :class:`~django.contrib.sessions.serializers.JSONSerializer`.
  490. * Session data is stored in a database table named ``django_session`` .
  491. * Django only sends a cookie if it needs to. If you don't set any session
  492. data, it won't send a session cookie.
  493. The ``SessionStore`` object
  494. ---------------------------
  495. When working with sessions internally, Django uses a session store object from
  496. the corresponding session engine. By convention, the session store object class
  497. is named ``SessionStore`` and is located in the module designated by
  498. :setting:`SESSION_ENGINE`.
  499. All ``SessionStore`` classes available in Django inherit from
  500. :class:`~backends.base.SessionBase` and implement data manipulation methods,
  501. namely:
  502. * ``exists()``
  503. * ``create()``
  504. * ``save()``
  505. * ``delete()``
  506. * ``load()``
  507. * :meth:`~backends.base.SessionBase.clear_expired`
  508. In order to build a custom session engine or to customize an existing one, you
  509. may create a new class inheriting from :class:`~backends.base.SessionBase` or
  510. any other existing ``SessionStore`` class.
  511. You can extend the session engines, but doing so with database-backed session
  512. engines generally requires some extra effort (see the next section for
  513. details).
  514. .. _extending-database-backed-session-engines:
  515. Extending database-backed session engines
  516. =========================================
  517. Creating a custom database-backed session engine built upon those included in
  518. Django (namely ``db`` and ``cached_db``) may be done by inheriting
  519. :class:`~base_session.AbstractBaseSession` and either ``SessionStore`` class.
  520. ``AbstractBaseSession`` and ``BaseSessionManager`` are importable from
  521. ``django.contrib.sessions.base_session`` so that they can be imported without
  522. including ``django.contrib.sessions`` in :setting:`INSTALLED_APPS`.
  523. .. class:: base_session.AbstractBaseSession
  524. The abstract base session model.
  525. .. attribute:: session_key
  526. Primary key. The field itself may contain up to 40 characters. The
  527. current implementation generates a 32-character string (a random
  528. sequence of digits and lowercase ASCII letters).
  529. .. attribute:: session_data
  530. A string containing an encoded and serialized session dictionary.
  531. .. attribute:: expire_date
  532. A datetime designating when the session expires.
  533. Expired sessions are not available to a user, however, they may still
  534. be stored in the database until the :djadmin:`clearsessions` management
  535. command is run.
  536. .. classmethod:: get_session_store_class()
  537. Returns a session store class to be used with this session model.
  538. .. method:: get_decoded()
  539. Returns decoded session data.
  540. Decoding is performed by the session store class.
  541. You can also customize the model manager by subclassing
  542. :class:`~django.contrib.sessions.base_session.BaseSessionManager`:
  543. .. class:: base_session.BaseSessionManager
  544. .. method:: encode(session_dict)
  545. Returns the given session dictionary serialized and encoded as a string.
  546. Encoding is performed by the session store class tied to a model class.
  547. .. method:: save(session_key, session_dict, expire_date)
  548. Saves session data for a provided session key, or deletes the session
  549. in case the data is empty.
  550. Customization of ``SessionStore`` classes is achieved by overriding methods
  551. and properties described below:
  552. .. class:: backends.db.SessionStore
  553. Implements database-backed session store.
  554. .. classmethod:: get_model_class()
  555. Override this method to return a custom session model if you need one.
  556. .. method:: create_model_instance(data)
  557. Returns a new instance of the session model object, which represents
  558. the current session state.
  559. Overriding this method provides the ability to modify session model
  560. data before it's saved to database.
  561. .. class:: backends.cached_db.SessionStore
  562. Implements cached database-backed session store.
  563. .. attribute:: cache_key_prefix
  564. A prefix added to a session key to build a cache key string.
  565. Example
  566. -------
  567. The example below shows a custom database-backed session engine that includes
  568. an additional database column to store an account ID (thus providing an option
  569. to query the database for all active sessions for an account)::
  570. from django.contrib.sessions.backends.db import SessionStore as DBStore
  571. from django.contrib.sessions.base_session import AbstractBaseSession
  572. from django.db import models
  573. class CustomSession(AbstractBaseSession):
  574. account_id = models.IntegerField(null=True, db_index=True)
  575. @classmethod
  576. def get_session_store_class(cls):
  577. return SessionStore
  578. class SessionStore(DBStore):
  579. @classmethod
  580. def get_model_class(cls):
  581. return CustomSession
  582. def create_model_instance(self, data):
  583. obj = super().create_model_instance(data)
  584. try:
  585. account_id = int(data.get('_auth_user_id'))
  586. except (ValueError, TypeError):
  587. account_id = None
  588. obj.account_id = account_id
  589. return obj
  590. If you are migrating from the Django's built-in ``cached_db`` session store to
  591. a custom one based on ``cached_db``, you should override the cache key prefix
  592. in order to prevent a namespace clash::
  593. class SessionStore(CachedDBStore):
  594. cache_key_prefix = 'mysessions.custom_cached_db_backend'
  595. # ...
  596. Session IDs in URLs
  597. ===================
  598. The Django sessions framework is entirely, and solely, cookie-based. It does
  599. not fall back to putting session IDs in URLs as a last resort, as PHP does.
  600. This is an intentional design decision. Not only does that behavior make URLs
  601. ugly, it makes your site vulnerable to session-ID theft via the "Referer"
  602. header.