Search code examples
pythonflasksession-cookieshttponly

Turn off HttpOnly for Flask Session for only one handler


I'm using Flask defaults so that HttpOnly is set for the session cookie.

I have one handler for which I'd like to allow JavaScript to access the session cookie.

Is there a way to change the Flask session cookie for a single handler so that HttpOnly is false?

I tried this in my handler:

app.config['SESSION_COOKIE_HTTPONLY'] = False
rsp = make_response(jsonify(...))
app.config['SESSION_COOKIE_HTTPONLY'] = True
return rsp

but the cookie still had HTTPONLY set. It looks like Flask adds the session cookie after making the response.


Solution

  • I figured out a solution using the info from this answer.

    You can create the session cookie data like this:

    from flask.sessions import SecureCookieSessionInterface
    session_serializer = SecureCookieSessionInterface().get_signing_serializer(app)
    session_clone = dict(foo='bar')
    session_cookie_data = session_serializer.dumps(session_clone)
    

    and you can then create your own cookie with the name session:

    resp = make_response()
    resp.set_cookie('session', session_cookie_data)
    return resp