Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 849
Michael David Watson Avatar asked Feb 16 '17 20:02

Michael David Watson


People also ask

How do you get the cookie value in Flask?

Flask cookies In Flask, set the cookie on the response object. Use the make_response() function to get the response object from the return value of the view function. After that, the cookie is stored using the set_cookie() function of the response object. It is easy to read back cookies.

Does Flask session use cookies?

The cookie used to store session data is known session cookie. However, unlike an ordinary cookie, Flask Cryptographically signs the session cookie. It means that anyone can view the contents of the cookie, but can't modify the cookie unless he has the secret key used to sign the cookie.

How do you set cookies in a Flask?

In Flask, cookies are set on response object. Use make_response() function to get response object from return value of a view function. After that, use the set_cookie() function of response object to store a cookie.


1 Answers

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() \
                        .get_signing_serializer(app)
    
@app.route("/")
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. [1]: https://github.com/pallets/flask/blob/0e79aba40d2497218736448ced708fcf4f8943b3/flask/sessions.py#L363

like image 149
Michael David Watson Avatar answered Sep 19 '22 18:09

Michael David Watson