Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does flask get the value back from session cookies?

I was looking at a cookie set through the session object in flask and it was just a hash (or it looked like it was just a hash). The value I set for the cookie was nowhere to be found but flask could get the value back.

I thought you had to store the value in the cookie alongside the hash (and then have a SECRET in your app to mix with the value for the hash), otherwise I don't know how you'd get your value back.

I thought maybe they hash the secret and the value and then encode it for extra obfuscation or something along those lines.

like image 928
jtht Avatar asked Sep 12 '25 02:09

jtht


1 Answers

The cookie value contains compressed and serialised data.

Flask does this to the data stored in the cookie:

  • Python data is serialised using (a customised form of) JSON.
  • The serialisation is cryptographically signed to ensure integrity
  • The signature plus serialisation is compressed (unless the compressed data would be larger than the uncompressed version) and base64 encoded.

On reading the cookie Flask only has to:

  • Decompress the data
  • Re-calculate the signature and validate it against the included signature
  • Load the serialised data back to Python objects.

Most of this is taken care of by itsdangerous. The JSON encoding and decoding is handled by the Flask session module.

Until recently, pickle was used to do the serialisation but that has security risks if the server-side secret was ever stolen. See Better Client-side sessions.

like image 187
Martijn Pieters Avatar answered Sep 14 '25 18:09

Martijn Pieters