sessions.txt 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  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_CLASSES` setting and make sure
  16. it contains ``'django.contrib.sessions.middleware.SessionMiddleware'``.
  17. The default ``settings.py`` created by ``django-admin.py startproject``
  18. has ``SessionMiddleware`` activated.
  19. If you don't want to use sessions, you might as well remove the
  20. ``SessionMiddleware`` line from :setting:`MIDDLEWARE_CLASSES` 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.
  49. If you have multiple caches defined in :setting:`CACHES`, Django will use the
  50. default cache. To use another cache, set :setting:`SESSION_CACHE_ALIAS` to the
  51. name of that cache.
  52. Once your cache is configured, you've got two choices for how to store data in
  53. the cache:
  54. * Set :setting:`SESSION_ENGINE` to
  55. ``"django.contrib.sessions.backends.cache"`` for a simple caching session
  56. store. Session data will be stored directly in your cache. However, session
  57. data may not be persistent: cached data can be evicted if the cache fills
  58. up or if the cache server is restarted.
  59. * For persistent, cached data, set :setting:`SESSION_ENGINE` to
  60. ``"django.contrib.sessions.backends.cached_db"``. This uses a
  61. write-through cache -- every write to the cache will also be written to
  62. the database. Session reads only use the database if the data is not
  63. already in the cache.
  64. Both session stores are quite fast, but the simple cache is faster because it
  65. disregards persistence. In most cases, the ``cached_db`` backend will be fast
  66. enough, but if you need that last bit of performance, and are willing to let
  67. session data be expunged from time to time, the ``cache`` backend is for you.
  68. If you use the ``cached_db`` session backend, you also need to follow the
  69. configuration instructions for the `using database-backed sessions`_.
  70. .. versionchanged:: 1.7
  71. Before version 1.7, the ``cached_db`` backend always used the ``default`` cache
  72. rather than the :setting:`SESSION_CACHE_ALIAS`.
  73. Using file-based sessions
  74. -------------------------
  75. To use file-based sessions, set the :setting:`SESSION_ENGINE` setting to
  76. ``"django.contrib.sessions.backends.file"``.
  77. You might also want to set the :setting:`SESSION_FILE_PATH` setting (which
  78. defaults to output from ``tempfile.gettempdir()``, most likely ``/tmp``) to
  79. control where Django stores session files. Be sure to check that your Web
  80. server has permissions to read and write to this location.
  81. .. _cookie-session-backend:
  82. Using cookie-based sessions
  83. ---------------------------
  84. To use cookies-based sessions, set the :setting:`SESSION_ENGINE` setting to
  85. ``"django.contrib.sessions.backends.signed_cookies"``. The session data will be
  86. stored using Django's tools for :doc:`cryptographic signing </topics/signing>`
  87. and the :setting:`SECRET_KEY` setting.
  88. .. note::
  89. When using cookies-based sessions :mod:`django.contrib.sessions` can be
  90. removed from :setting:`INSTALLED_APPS` setting because data is loaded
  91. from the key itself and not from the database, so there is no need for the
  92. creation and usage of ``django.contrib.sessions.models.Session`` table.
  93. .. note::
  94. It's recommended to leave the :setting:`SESSION_COOKIE_HTTPONLY` setting
  95. ``True`` to prevent tampering of the stored data from JavaScript.
  96. .. warning::
  97. **If the SECRET_KEY is not kept secret and you are using the**
  98. :class:`~django.contrib.sessions.serializers.PickleSerializer`, **this can
  99. lead to arbitrary remote code execution.**
  100. An attacker in possession of the :setting:`SECRET_KEY` can not only
  101. generate falsified session data, which your site will trust, but also
  102. remotely execute arbitrary code, as the data is serialized using pickle.
  103. If you use cookie-based sessions, pay extra care that your secret key is
  104. always kept completely secret, for any system which might be remotely
  105. accessible.
  106. **The session data is signed but not encrypted**
  107. When using the cookies backend the session data can be read by the client.
  108. A MAC (Message Authentication Code) is used to protect the data against
  109. changes by the client, so that the session data will be invalidated when being
  110. tampered with. The same invalidation happens if the client storing the
  111. cookie (e.g. your user's browser) can't store all of the session cookie and
  112. drops data. Even though Django compresses the data, it's still entirely
  113. possible to exceed the `common limit of 4096 bytes`_ per cookie.
  114. **No freshness guarantee**
  115. Note also that while the MAC can guarantee the authenticity of the data
  116. (that it was generated by your site, and not someone else), and the
  117. integrity of the data (that it is all there and correct), it cannot
  118. guarantee freshness i.e. that you are being sent back the last thing you
  119. sent to the client. This means that for some uses of session data, the
  120. cookie backend might open you up to `replay attacks`_. Unlike other session
  121. backends which keep a server-side record of each session and invalidate it
  122. when a user logs out, cookie-based sessions are not invalidated when a user
  123. logs out. Thus if an attacker steals a user's cookie, he or she can use that
  124. cookie to login as that user even if the user logs out. Cookies will only
  125. be detected as 'stale' if they are older than your
  126. :setting:`SESSION_COOKIE_AGE`.
  127. **Performance**
  128. Finally, the size of a cookie can have an impact on the `speed of your site`_.
  129. .. _`common limit of 4096 bytes`: http://tools.ietf.org/html/rfc2965#section-5.3
  130. .. _`replay attacks`: http://en.wikipedia.org/wiki/Replay_attack
  131. .. _`speed of your site`: http://yuiblog.com/blog/2007/03/01/performance-research-part-3/
  132. Using sessions in views
  133. =======================
  134. When ``SessionMiddleware`` is activated, each :class:`~django.http.HttpRequest`
  135. object -- the first argument to any Django view function -- will have a
  136. ``session`` attribute, which is a dictionary-like object.
  137. You can read it and write to ``request.session`` at any point in your view.
  138. You can edit it multiple times.
  139. .. class:: backends.base.SessionBase
  140. This is the base class for all session objects. It has the following
  141. standard dictionary methods:
  142. .. method:: __getitem__(key)
  143. Example: ``fav_color = request.session['fav_color']``
  144. .. method:: __setitem__(key, value)
  145. Example: ``request.session['fav_color'] = 'blue'``
  146. .. method:: __delitem__(key)
  147. Example: ``del request.session['fav_color']``. This raises ``KeyError``
  148. if the given ``key`` isn't already in the session.
  149. .. method:: __contains__(key)
  150. Example: ``'fav_color' in request.session``
  151. .. method:: get(key, default=None)
  152. Example: ``fav_color = request.session.get('fav_color', 'red')``
  153. .. method:: pop(key)
  154. Example: ``fav_color = request.session.pop('fav_color')``
  155. .. method:: keys
  156. .. method:: items
  157. .. method:: setdefault
  158. .. method:: clear
  159. It also has these methods:
  160. .. method:: flush
  161. Delete the current session data from the session and regenerate the
  162. session key value that is sent back to the user in the cookie. This is
  163. used if you want to ensure that the previous session data can't be
  164. accessed again from the user's browser (for example, the
  165. :func:`django.contrib.auth.logout()` function calls it).
  166. .. method:: set_test_cookie
  167. Sets a test cookie to determine whether the user's browser supports
  168. cookies. Due to the way cookies work, you won't be able to test this
  169. until the user's next page request. See `Setting test cookies`_ below for
  170. more information.
  171. .. method:: test_cookie_worked
  172. Returns either ``True`` or ``False``, depending on whether the user's
  173. browser accepted the test cookie. Due to the way cookies work, you'll
  174. have to call ``set_test_cookie()`` on a previous, separate page request.
  175. See `Setting test cookies`_ below for more information.
  176. .. method:: delete_test_cookie
  177. Deletes the test cookie. Use this to clean up after yourself.
  178. .. method:: set_expiry(value)
  179. Sets the expiration time for the session. You can pass a number of
  180. different values:
  181. * If ``value`` is an integer, the session will expire after that
  182. many seconds of inactivity. For example, calling
  183. ``request.session.set_expiry(300)`` would make the session expire
  184. in 5 minutes.
  185. * If ``value`` is a ``datetime`` or ``timedelta`` object, the
  186. session will expire at that specific date/time. Note that ``datetime``
  187. and ``timedelta`` values are only serializable if you are using the
  188. :class:`~django.contrib.sessions.serializers.PickleSerializer`.
  189. * If ``value`` is ``0``, the user's session cookie will expire
  190. when the user's Web browser is closed.
  191. * If ``value`` is ``None``, the session reverts to using the global
  192. session expiry policy.
  193. Reading a session is not considered activity for expiration
  194. purposes. Session expiration is computed from the last time the
  195. session was *modified*.
  196. .. method:: get_expiry_age
  197. Returns the number of seconds until this session expires. For sessions
  198. with no custom expiration (or those set to expire at browser close), this
  199. will equal :setting:`SESSION_COOKIE_AGE`.
  200. This function accepts two optional keyword arguments:
  201. - ``modification``: last modification of the session, as a
  202. :class:`~datetime.datetime` object. Defaults to the current time.
  203. - ``expiry``: expiry information for the session, as a
  204. :class:`~datetime.datetime` object, an :func:`int` (in seconds), or
  205. ``None``. Defaults to the value stored in the session by
  206. :meth:`set_expiry`, if there is one, or ``None``.
  207. .. method:: get_expiry_date
  208. Returns the date this session will expire. For sessions with no custom
  209. expiration (or those set to expire at browser close), this will equal the
  210. date :setting:`SESSION_COOKIE_AGE` seconds from now.
  211. This function accepts the same keyword arguments as :meth:`get_expiry_age`.
  212. .. method:: get_expire_at_browser_close
  213. Returns either ``True`` or ``False``, depending on whether the user's
  214. session cookie will expire when the user's Web browser is closed.
  215. .. method:: clear_expired
  216. Removes expired sessions from the session store. This class method is
  217. called by :djadmin:`clearsessions`.
  218. .. method:: cycle_key
  219. Creates a new session key while retaining the current session data.
  220. :func:`django.contrib.auth.login()` calls this method to mitigate against
  221. session fixation.
  222. .. _session_serialization:
  223. Session serialization
  224. ---------------------
  225. .. versionchanged:: 1.6
  226. Before version 1.6, Django defaulted to using :mod:`pickle` to serialize
  227. session data before storing it in the backend. If you're using the :ref:`signed
  228. cookie session backend<cookie-session-backend>` and :setting:`SECRET_KEY` is
  229. known by an attacker (there isn't an inherent vulnerability in Django that
  230. would cause it to leak), the attacker could insert a string into his session
  231. which, when unpickled, executes arbitrary code on the server. The technique for
  232. doing so is simple and easily available on the internet. Although the cookie
  233. session storage signs the cookie-stored data to prevent tampering, a
  234. :setting:`SECRET_KEY` leak immediately escalates to a remote code execution
  235. vulnerability.
  236. This attack can be mitigated by serializing session data using JSON rather
  237. than :mod:`pickle`. To facilitate this, Django 1.5.3 introduced a new setting,
  238. :setting:`SESSION_SERIALIZER`, to customize the session serialization format.
  239. For backwards compatibility, this setting defaults to
  240. using :class:`django.contrib.sessions.serializers.PickleSerializer` in
  241. Django 1.5.x, but, for security hardening, defaults to
  242. :class:`django.contrib.sessions.serializers.JSONSerializer` in Django 1.6.
  243. Even with the caveats described in :ref:`custom-serializers`, we highly
  244. recommend sticking with JSON serialization *especially if you are using the
  245. cookie backend*.
  246. Bundled Serializers
  247. ^^^^^^^^^^^^^^^^^^^
  248. .. class:: serializers.JSONSerializer
  249. A wrapper around the JSON serializer from :mod:`django.core.signing`. Can
  250. only serialize basic data types.
  251. In addition, as JSON supports only string keys, note that using non-string
  252. keys in ``request.session`` won't work as expected::
  253. >>> # initial assignment
  254. >>> request.session[0] = 'bar'
  255. >>> # subsequent requests following serialization & deserialization
  256. >>> # of session data
  257. >>> request.session[0] # KeyError
  258. >>> request.session['0']
  259. 'bar'
  260. See the :ref:`custom-serializers` section for more details on limitations
  261. of JSON serialization.
  262. .. class:: serializers.PickleSerializer
  263. Supports arbitrary Python objects, but, as described above, can lead to a
  264. remote code execution vulnerability if :setting:`SECRET_KEY` becomes known
  265. by an attacker.
  266. .. _custom-serializers:
  267. Write Your Own Serializer
  268. ^^^^^^^^^^^^^^^^^^^^^^^^^
  269. Note that unlike :class:`~django.contrib.sessions.serializers.PickleSerializer`,
  270. the :class:`~django.contrib.sessions.serializers.JSONSerializer` cannot handle
  271. arbitrary Python data types. As is often the case, there is a trade-off between
  272. convenience and security. If you wish to store more advanced data types
  273. including ``datetime`` and ``Decimal`` in JSON backed sessions, you will need
  274. to write a custom serializer (or convert such values to a JSON serializable
  275. object before storing them in ``request.session``). While serializing these
  276. values is fairly straightforward
  277. (``django.core.serializers.json.DateTimeAwareJSONEncoder`` may be helpful),
  278. writing a decoder that can reliably get back the same thing that you put in is
  279. more fragile. For example, you run the risk of returning a ``datetime`` that
  280. was actually a string that just happened to be in the same format chosen for
  281. ``datetime``\s).
  282. Your serializer class must implement two methods,
  283. ``dumps(self, obj)`` and ``loads(self, data)``, to serialize and deserialize
  284. the dictionary of session data, respectively.
  285. Session object guidelines
  286. -------------------------
  287. * Use normal Python strings as dictionary keys on ``request.session``. This
  288. is more of a convention than a hard-and-fast rule.
  289. * Session dictionary keys that begin with an underscore are reserved for
  290. internal use by Django.
  291. * Don't override ``request.session`` with a new object, and don't access or
  292. set its attributes. Use it like a Python dictionary.
  293. Examples
  294. --------
  295. This simplistic view sets a ``has_commented`` variable to ``True`` after a user
  296. posts a comment. It doesn't let a user post a comment more than once::
  297. def post_comment(request, new_comment):
  298. if request.session.get('has_commented', False):
  299. return HttpResponse("You've already commented.")
  300. c = comments.Comment(comment=new_comment)
  301. c.save()
  302. request.session['has_commented'] = True
  303. return HttpResponse('Thanks for your comment!')
  304. This simplistic view logs in a "member" of the site::
  305. def login(request):
  306. m = Member.objects.get(username=request.POST['username'])
  307. if m.password == request.POST['password']:
  308. request.session['member_id'] = m.id
  309. return HttpResponse("You're logged in.")
  310. else:
  311. return HttpResponse("Your username and password didn't match.")
  312. ...And this one logs a member out, according to ``login()`` above::
  313. def logout(request):
  314. try:
  315. del request.session['member_id']
  316. except KeyError:
  317. pass
  318. return HttpResponse("You're logged out.")
  319. The standard :meth:`django.contrib.auth.logout` function actually does a bit
  320. more than this to prevent inadvertent data leakage. It calls the
  321. :meth:`~backends.base.SessionBase.flush` method of ``request.session``.
  322. We are using this example as a demonstration of how to work with session
  323. objects, not as a full ``logout()`` implementation.
  324. Setting test cookies
  325. ====================
  326. As a convenience, Django provides an easy way to test whether the user's
  327. browser accepts cookies. Just call the
  328. :meth:`~backends.base.SessionBase.set_test_cookie` method of
  329. ``request.session`` in a view, and call
  330. :meth:`~backends.base.SessionBase.test_cookie_worked` in a subsequent view --
  331. not in the same view call.
  332. This awkward split between ``set_test_cookie()`` and ``test_cookie_worked()``
  333. is necessary due to the way cookies work. When you set a cookie, you can't
  334. actually tell whether a browser accepted it until the browser's next request.
  335. It's good practice to use
  336. :meth:`~backends.base.SessionBase.delete_test_cookie()` to clean up after
  337. yourself. Do this after you've verified that the test cookie worked.
  338. Here's a typical usage example::
  339. def login(request):
  340. if request.method == 'POST':
  341. if request.session.test_cookie_worked():
  342. request.session.delete_test_cookie()
  343. return HttpResponse("You're logged in.")
  344. else:
  345. return HttpResponse("Please enable cookies and try again.")
  346. request.session.set_test_cookie()
  347. return render_to_response('foo/login_form.html')
  348. Using sessions out of views
  349. ===========================
  350. .. note::
  351. The examples in this section import the ``SessionStore`` object directly
  352. from the ``django.contrib.sessions.backends.db`` backend. In your own code,
  353. you should consider importing ``SessionStore`` from the session engine
  354. designated by :setting:`SESSION_ENGINE`, as below:
  355. >>> from importlib import import_module
  356. >>> from django.conf import settings
  357. >>> SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
  358. An API is available to manipulate session data outside of a view::
  359. >>> from django.contrib.sessions.backends.db import SessionStore
  360. >>> import datetime
  361. >>> s = SessionStore()
  362. >>> # stored as seconds since epoch since datetimes are not serializable in JSON.
  363. >>> s['last_login'] = 1376587691
  364. >>> s.save()
  365. >>> s.session_key
  366. '2b1189a188b44ad18c35e113ac6ceead'
  367. >>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
  368. >>> s['last_login']
  369. 1376587691
  370. In order to mitigate session fixation attacks, sessions keys that don't exist
  371. are regenerated::
  372. >>> from django.contrib.sessions.backends.db import SessionStore
  373. >>> s = SessionStore(session_key='no-such-session-here')
  374. >>> s.save()
  375. >>> s.session_key
  376. 'ff882814010ccbc3c870523934fee5a2'
  377. If you're using the ``django.contrib.sessions.backends.db`` backend, each
  378. session is just a normal Django model. The ``Session`` model is defined in
  379. ``django/contrib/sessions/models.py``. Because it's a normal model, you can
  380. access sessions using the normal Django database API::
  381. >>> from django.contrib.sessions.models import Session
  382. >>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
  383. >>> s.expire_date
  384. datetime.datetime(2005, 8, 20, 13, 35, 12)
  385. Note that you'll need to call ``get_decoded()`` to get the session dictionary.
  386. This is necessary because the dictionary is stored in an encoded format::
  387. >>> s.session_data
  388. 'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
  389. >>> s.get_decoded()
  390. {'user_id': 42}
  391. When sessions are saved
  392. =======================
  393. By default, Django only saves to the session database when the session has been
  394. modified -- that is if any of its dictionary values have been assigned or
  395. deleted::
  396. # Session is modified.
  397. request.session['foo'] = 'bar'
  398. # Session is modified.
  399. del request.session['foo']
  400. # Session is modified.
  401. request.session['foo'] = {}
  402. # Gotcha: Session is NOT modified, because this alters
  403. # request.session['foo'] instead of request.session.
  404. request.session['foo']['bar'] = 'baz'
  405. In the last case of the above example, we can tell the session object
  406. explicitly that it has been modified by setting the ``modified`` attribute on
  407. the session object::
  408. request.session.modified = True
  409. To change this default behavior, set the :setting:`SESSION_SAVE_EVERY_REQUEST`
  410. setting to ``True``. When set to ``True``, Django will save the session to the
  411. database on every single request.
  412. Note that the session cookie is only sent when a session has been created or
  413. modified. If :setting:`SESSION_SAVE_EVERY_REQUEST` is ``True``, the session
  414. cookie will be sent on every request.
  415. Similarly, the ``expires`` part of a session cookie is updated each time the
  416. session cookie is sent.
  417. The session is not saved if the response's status code is 500.
  418. .. _browser-length-vs-persistent-sessions:
  419. Browser-length sessions vs. persistent sessions
  420. ===============================================
  421. You can control whether the session framework uses browser-length sessions vs.
  422. persistent sessions with the :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`
  423. setting.
  424. By default, :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``False``,
  425. which means session cookies will be stored in users' browsers for as long as
  426. :setting:`SESSION_COOKIE_AGE`. Use this if you don't want people to have to
  427. log in every time they open a browser.
  428. If :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``True``, Django will
  429. use browser-length cookies -- cookies that expire as soon as the user closes
  430. his or her browser. Use this if you want people to have to log in every time
  431. they open a browser.
  432. This setting is a global default and can be overwritten at a per-session level
  433. by explicitly calling the :meth:`~backends.base.SessionBase.set_expiry` method
  434. of ``request.session`` as described above in `using sessions in views`_.
  435. .. note::
  436. Some browsers (Chrome, for example) provide settings that allow users to
  437. continue browsing sessions after closing and re-opening the browser. In
  438. some cases, this can interfere with the
  439. :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` setting and prevent sessions
  440. from expiring on browser close. Please be aware of this while testing
  441. Django applications which have the
  442. :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` setting enabled.
  443. Clearing the session store
  444. ==========================
  445. As users create new sessions on your website, session data can accumulate in
  446. your session store. If you're using the database backend, the
  447. ``django_session`` database table will grow. If you're using the file backend,
  448. your temporary directory will contain an increasing number of files.
  449. To understand this problem, consider what happens with the database backend.
  450. When a user logs in, Django adds a row to the ``django_session`` database
  451. table. Django updates this row each time the session data changes. If the user
  452. logs out manually, Django deletes the row. But if the user does *not* log out,
  453. the row never gets deleted. A similar process happens with the file backend.
  454. Django does *not* provide automatic purging of expired sessions. Therefore,
  455. it's your job to purge expired sessions on a regular basis. Django provides a
  456. clean-up management command for this purpose: :djadmin:`clearsessions`. It's
  457. recommended to call this command on a regular basis, for example as a daily
  458. cron job.
  459. Note that the cache backend isn't vulnerable to this problem, because caches
  460. automatically delete stale data. Neither is the cookie backend, because the
  461. session data is stored by the users' browsers.
  462. Settings
  463. ========
  464. A few :ref:`Django settings <settings-sessions>` give you control over session
  465. behavior:
  466. * :setting:`SESSION_CACHE_ALIAS`
  467. * :setting:`SESSION_COOKIE_AGE`
  468. * :setting:`SESSION_COOKIE_DOMAIN`
  469. * :setting:`SESSION_COOKIE_HTTPONLY`
  470. * :setting:`SESSION_COOKIE_NAME`
  471. * :setting:`SESSION_COOKIE_PATH`
  472. * :setting:`SESSION_COOKIE_SECURE`
  473. * :setting:`SESSION_ENGINE`
  474. * :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`
  475. * :setting:`SESSION_FILE_PATH`
  476. * :setting:`SESSION_SAVE_EVERY_REQUEST`
  477. .. _topics-session-security:
  478. Session security
  479. ================
  480. Subdomains within a site are able to set cookies on the client for the whole
  481. domain. This makes session fixation possible if all subdomains are not
  482. controlled by trusted users (or, are at least unable to set cookies).
  483. For example, an attacker could log into ``good.example.com`` and get a valid
  484. session for his account. If the attacker has control over ``bad.example.com``,
  485. he can use it to send his session key to you since a subdomain is permitted
  486. to set cookies on `*.example.com``. When you visit ``good.example.com``,
  487. you'll be logged in as the attacker and might inadvertently enter your
  488. sensitive personal data (e.g. credit card info) into the attackers account.
  489. Another possible attack would be if ``good.example.com`` sets its
  490. :setting:`SESSION_COOKIE_DOMAIN` to ``".example.com"`` which would cause
  491. session cookies from that site to be sent to ``bad.example.com``.
  492. Technical details
  493. =================
  494. * The session dictionary accepts any :mod:`json` serializable value when using
  495. :class:`~django.contrib.sessions.serializers.JSONSerializer` or any
  496. pickleable Python object when using
  497. :class:`~django.contrib.sessions.serializers.PickleSerializer`. See the
  498. :mod:`pickle` module for more information.
  499. * Session data is stored in a database table named ``django_session`` .
  500. * Django only sends a cookie if it needs to. If you don't set any session
  501. data, it won't send a session cookie.
  502. Session IDs in URLs
  503. ===================
  504. The Django sessions framework is entirely, and solely, cookie-based. It does
  505. not fall back to putting session IDs in URLs as a last resort, as PHP does.
  506. This is an intentional design decision. Not only does that behavior make URLs
  507. ugly, it makes your site vulnerable to session-ID theft via the "Referer"
  508. header.