Generating signed session cookie value used in Flask


I’m proxying a Flask server with another Flask server that needs to inject items into the session.

Both servers have the same secret key so the cryptographic signature will be the same. When using Flask and a session, the http response contains a Set-Cookie header with session=text, where text is an encoded JSON string of your session object that is signed using you secret key.

Essentially, I need to be able to re-create this string, but I can’t find the interface to do so.


I ended up solving my own issue after finding [how flask does this][1] in the source. I was in a hurry at work so did not have time to better explain.

from flask import Flask, session
from flask.sessions import SecureCookieSessionInterface
app = Flask("example")
app.secret_key = "Tom Izzo 4 President"

# 1. this is what I was looking for
session_serializer = SecureCookieSessionInterface() \
def test():
    session["lst"] = ["a", "b", "c", "d"]

    # 2. and this is how I needed to use it
    session_cookie = session_serializer.dumps(dict(session))

The variable session_cookie above is a valid cookie value for a session using the given secret_key. With this I am able to forward a request to another flask server that uses the secret_key.

Answered By – Michael David Watson

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published