How does Flask Sessions work?

Flask generates the session cookie using its sister project, It's Dangerous. The project page has a great overview of how It's Dangerous works, but at a high level:

  • the data in your session (set by session["username"] = "EndenDragon") is serialized into a JSON string ({"username":"EndenDragon"})
  • that string is encoded using base64 encoding (eyJ1c2VybmFtZSI6IkVuZGVuRHJhZ29uIn0=). This makes it safe for use cases like an email verification link, where it might be appended at the end of the link.
  • the base64 encoded data has a "." appended to it. The timestamp when the session was created is base64 encoded and appended to it.
  • A cryptographic signature is generated for the session + timestamp, using your secret key. The signature to the session value after a "." as well.

The value is then sent to the browser as a Cookie in the response.

The values in the session can be read by end users (and over insecure connections). The server can verify cookies it receives hasn't been tampered with, without storing anything on its end. It just recomputes the signature from the session + timestamp part of the session value, and makes sure it matches the signature at the end of the session value.

The inclusion of the timestamp enables Flask to enforce the expiration date of permanent sessions on the server side, in addition to setting an expiration date on the client side.

Addendum

Users can easily read the values in the session by decoding the first part of the session value. Go to the "Storage" or "Application" tab in developer tools, look for the "session" cookie, copy the value up to the first period, and run btoa(<session-part>) in the Console.


The default session is implemented using secure cookies. Cookies are persisted by the client's browser, Flask doesn't do anything in that regard. Each client has a unique session cookie, which it sends to the Flask server with each request.

The cookie is secure not encrypted, it does not prevent anyone with the cookie from viewing the data, only from modifying it. Flask signs the data with the app's secret key when sending it, and unsigns it with the same key when reading it.

Flask does not add anything to the session. There is no session id, the browser just sends the session cookie during each request, and Flask reads it.

You can write your own session interface to change how the session works. See extensions such as Flask-Session

Tags:

Session

Flask