Can't get variable from session using SessionMiddleware in FastAPI

Question:

I am trying to make a primitive authorization by session, here is a sample code

import uvicorn
from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="some-random-string", max_age=0)


@app.get("/a")
async def session_set(request: Request):
    request.session["my_var"] = "1234"
    return 'ok'


@app.get("/b")
async def session_info(request: Request):
    my_var = request.session.get("my_var", None)
    return my_var


if __name__ == '__main__':
    uvicorn.run('http-session:app', port=5000, reload=True)

The session is set, everything is fine, but the session_info endpoint returns an empty dictionary. Can you explain to me what am I doing wrong?

Asked By: 28 Lucky

||

Answers:

As per Starlette documentation on SessionMiddleware:

  • max_age – Session expiry time in seconds. Defaults to 2 weeks. If
    set to None then the cookie will last as long as the browser session.

  • same_site – SameSite flag prevents the browser from sending session
    cookie along with cross-site requests. Defaults to 'lax'.

  • https_only – Indicate that Secure flag should be set (can be used
    with HTTPS only). Defaults to False.

Hence, using max_age=0 simply results in the session cookie getting instantly expired (see this answer as well). You can either remove max_age when calling app.add_middleware() function, or adjust it as desired. Additionally, you may consider adjusting the same_site and https_only flags as well, in order to provide some protecttion to the session cookie (see this answer for more details).

Answered By: Chris