| 1 |
.. currentmodule:: flask_session |
| 2 |
|
| 3 |
Security |
| 4 |
========== |
| 5 |
|
| 6 |
.. warning:: |
| 7 |
|
| 8 |
Flask is a micro-framework and does not provide all security features out of the box. It is important to configure security settings for your application. |
| 9 |
|
| 10 |
Flask configuration |
| 11 |
-------------------- |
| 12 |
|
| 13 |
Please refer to documentation for `Flask`_, `OWASP`_, and other resources such as `MDN`_ for the latest information on best practice. |
| 14 |
|
| 15 |
Consider the following Flask configurations in production: |
| 16 |
|
| 17 |
.. list-table:: |
| 18 |
:header-rows: 1 |
| 19 |
:align: left |
| 20 |
|
| 21 |
* - Setting |
| 22 |
- Consideration |
| 23 |
* - SESSION_COOKIE_SECURE |
| 24 |
- Set to ``True`` if your application is served over HTTPS. |
| 25 |
* - SESSION_COOKIE_NAME |
| 26 |
- Use ``__Secure-`` or ``__Host-`` prefix according to MDN docs. |
| 27 |
* - SESSION_COOKIE_SAMESITE |
| 28 |
- Use ``Lax`` or ``Strict`` |
| 29 |
|
| 30 |
You can use a security plugin such as `Flask-Talisman`_ to set these and more. |
| 31 |
|
| 32 |
Storage |
| 33 |
------------------ |
| 34 |
|
| 35 |
Take care to secure your storage and storage client connection. For example, setup SSL/TLS and storage authentication. |
| 36 |
|
| 37 |
|
| 38 |
Session fixation |
| 39 |
------------------ |
| 40 |
|
| 41 |
Session fixation is an attack that permits an attacker to hijack a valid user session. The attacker can fixate a user's session by providing them with a session identifier. The attacker can then use the session identifier to impersonate the user. |
| 42 |
As one tool among others that can mitigate session fixation, is regenerating the session identifier when a user logs in. This can be done by calling the :meth:`flask.Flask.session_interface.regenerate` method. This method is defined in :class:`flask_session.base.ServerSideSession`. |
| 43 |
|
| 44 |
.. code-block:: python |
| 45 |
|
| 46 |
@app.route('/login') |
| 47 |
def login(): |
| 48 |
# your login logic ... |
| 49 |
app.session_interface.regenerate(session) |
| 50 |
# your response ... |
| 51 |
|
| 52 |
.. _Flask: https://flask.palletsprojects.com/en/2.3.x/security/#set-cookie-options |
| 53 |
.. _MDN: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies |
| 54 |
.. _OWASP: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html |
| 55 |
.. _Flask-Talisman: https://github.com/wntrblm/flask-talisman |