Add Session Management
Set up session management so the app can start tracking a user's authenticated state.
Now we'll add the ability to manage authenticated user sessions across requests. For more details on how session management works, please view our Session Management documentation.
Do you need session management?
Short answer: Yes.
While session management is technically optional, it's very strongly recommended. Without session management, the user's authenticated state would be lost on each each request and they'd have to continually re-authenticate.
Configure Session Middleware
Configure the SDK's SessionMiddleware
to enable encrypted, cookie-based sessions. The session for each authenticated user will be accessible on the request.state.session
field throughout your FastAPI routes. As part of the configuration, you'll need to provide a password that is at least 32 characters long. To generate the password, you can use: https://1password.com/password-generator.
Secure Cookies in Local Development (Sessions)
If session cookies fail to set on
http://localhost
, you can temporarily setsecure=False
inSessionMiddleware
. Always restoresecure=True
in production to protect session data.
# src/main.py
from fastapi import FastAPI
from wristband.fastapi_auth import SessionMiddleware
def create_app() -> FastAPI:
app = FastAPI()
# Make encrypted cookie-based sessions available on all routes.
app.add_middleware(SessionMiddleware, secret_key="<your-generated-pw>")
# Your other application setup...
Updated about 8 hours ago
Next, you'll use the Wristband SDK to create the necessary authentication endpoints in your FastAPI server.