简体   繁体   中英

How can a session cookie from Flask-0.10 be deserialized manually?

I have the raw value of a session cookie from a Flask-0.10 application. I need to read the session in another application that is not using Flask, so I don't have access to the session proxy.

In Flask-0.9 I could do the following:

session = SecureCookieSession.unserialize(cookie, app.secret_key)

However, this method no longer exists in Flask-0.10. How can I read the cookie data now?

Flask-0.10 switched to itsdangerous for serializing the session. See the relevant source code for how the session is read in Flask.

If you have a session serialized by Flask's default session interface, you can read it manually as follows.

Assuming your secret key is 'dev' , the session data {'hello': 'world'} is serialized to 'eyJoZWxsbyI6IndvcmxkIn0.BwEv5w.o3gYYutryNy7di1E3LbJZbCFGfY' .

from hashlib import sha1
from flask.sessions import session_json_serializer
from itsdangerous import URLSafeTimedSerializer

s = URLSafeTimedSerializer(
    'dev', salt='cookie-session',
    serializer=session_json_serializer,
    signer_kwargs={'key_derivation': 'hmac', 'digest_method': sha1}
)
session_data = s.loads('eyJoZWxsbyI6IndvcmxkIn0.BwEv5w.o3gYYutryNy7di1E3LbJZbCFGfY')
assert session_data['hello'] == 'world'  # True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM