Suppose you're logged in flask-login, It is essential to know what data is being stored in Flask cookies.
Get cookie
- Using chrome browser, you may right click and go to "Inspect"
- Click on "Application"
- Under "Storage", you will see "Cookies" with list of cookies listed within
- If you see a cookie value starting with a period, for example in the picture, you will find that cookie is compressed.
- 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'
- Now follow above steps to capture the cooke value
- In my case its following
- Copy the value of the cookie only till the first period (.)
- eyJmb28iOiJiYXIifQ.YJWcHA.8yt1Cf4sDsHfEgVQQztrDa3lw-I
- Now as you can see that cookie value did not start with period (.)
- We can simply copy the part of the string until the very first period (.)
- eyJmb28iOiJiYXIifQ
- Now lets go to Console window and type following
- atob("eyJmb28iOiJiYXIifQ")
- You will see the result in json rendering
- "{\"foo\":\"bar\"}"
Uncompressed ( Method 2)
- Using python
- You can use base64 module to decode session data
- Simply add three "===" as padding to satisfy base64 encoding string requirement
- Now you can simply run as following
>>> import base64
>>> base64.urlsafe_b64decode('eyJmb28iOiJiYXIifQ===')
b'{"foo":"bar"}'
Compressed
- Flask-Login compress the session data, but that does not mean its not readable
- Once you login with Flask login, you will see cookie value starting with period (".")
- we will use same method as above but simply decompress the data as such
- 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
- btoa()
- The btoa() method encodes a string in base-64.
- atob()
- The atob() method decodes a base-64 encoded string.
btoa("Hello World")
"SGVsbG8gV29ybGQ="
atob("SGVsbG8gV29ybGQ=")
"Hello World"