Created On: May 07, 2021, Last Updated On: May 07, 2021

Flask Cookies - Session

Public

How to decode flask cookies

By Ozzie Ghani3 new


Suppose you're logged in flask-login, It is essential to know what data is being stored in Flask cookies. 

Get cookie
  1. Using chrome browser, you may right click and go to "Inspect"
  2. Click on "Application" 
  3. Under "Storage", you will see "Cookies" with list of cookies listed within
  4. If you see a cookie value starting with a period, for example in the picture, you will find that cookie is compressed. 
  5. If the cookie is not compressed, you could use "Console" to decode.


Decode 
Uncompressed ( Method 1 )

I simply added following route to add a new session data 

@app.route('/sess')
def sess():
    session["foo"] = "bar"
    return f'Session Set'

  1. Now follow above steps to capture the cooke value
  2. In my case its following 
  3. Copy the value of the cookie only till the first period (.)
    1. eyJmb28iOiJiYXIifQ.YJWcHA.8yt1Cf4sDsHfEgVQQztrDa3lw-I
  4. Now as you can see that cookie value did not start with period (.)
  5. We can simply copy the part of the string until the very first period (.)
    1. eyJmb28iOiJiYXIifQ
  6. Now lets go to Console window and type following
  7. atob("eyJmb28iOiJiYXIifQ")
  8. You will see the result in json rendering 
    1. "{\"foo\":\"bar\"}"

Uncompressed ( Method 2)
  1. Using python
  2. You can use base64 module to decode session data 
  3. Simply add three "===" as padding to satisfy base64 encoding string requirement
  4. Now you can simply run as following
>>> import base64
>>> base64.urlsafe_b64decode('eyJmb28iOiJiYXIifQ===')
b'{"foo":"bar"}'


Compressed 
  1. Flask-Login compress the session data, but that does not mean its not readable
  2. Once you login with Flask login, you will see cookie value starting with period (".")
  3. we will use same method as above but simply decompress the data as such 
  4. For simplicity purpose, I will remove lengthy string 


>>> import base64
>>> import zlib
>>> d = "eJ........Ywug==="
>>> zlib.decompress(base64.urlsafe_b64decode(d))
b'{"_fresh":true,"_id":"3f00c......12144b","_user_id":"1","foo":"bar"}'


Securing Session

Flask-Session offers a really decent solution to disable readability of the session data from cookie


from flask_session import Session

""" 
I like redis and highly recommend using redis for storing this type of data 
#app.config['SESSION_TYPE'] = 'redis'
But for this example we will use sqlalchmy
"""


app.config['SESSION_TYPE'] = 'sqlalchemy'
app.config['SESSION_SQLALCHEMY'] = db

Session(app)

# of if you are using modularized approach 
You can use
sess = Session()
sess.init_app(app)


Encoding and Decoding in Javascript
  1. btoa()
    1. The btoa() method encodes a string in base-64.
  2. atob()
    1. The atob() method decodes a base-64 encoded string.


btoa("Hello World")
"SGVsbG8gV29ybGQ="

atob("SGVsbG8gV29ybGQ=")
"Hello World"