sessions.txt 34 KB

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