Skip to content
Scalekit Docs

FastAPI session middleware

Add hosted login and an encrypted session cookie to FastAPI with ScalekitAuth

Use ScalekitAuth from scalekit.frameworks.fastapi to add hosted login, an encrypted sk_session cookie, token refresh, and logout.

Typical flow: install the fastapi extra, call auth.install(app), and protect an endpoint with Depends(auth.requires_auth).

Requires scalekit-sdk-python 2.17.0 or later.

Register these URLs in the Scalekit Dashboard under Authentication > Redirects before you test:

Dashboard fieldMust match
Redirect URIredirect_uri exactly, for example http://localhost:5001/callback
Post Logout Redirect URIAbsolute URL after full logout, for example http://localhost:5001/
Initiate Login URLLogin path, for example http://localhost:5001/login

Store credentials in environment variables. Never hard-code secrets.

.env
SCALEKIT_ENVIRONMENT_URL=https://your-env.scalekit.com
SCALEKIT_CLIENT_ID=skc_...
SCALEKIT_CLIENT_SECRET=...
COOKIE_ENCRYPTION_SECRET= # openssl rand -base64 32
REDIRECT_URI=http://localhost:5001/callback

Keep COOKIE_ENCRYPTION_SECRET identical on every server instance.

Terminal
pip install "scalekit-sdk-python[fastapi]"
app.py
import os
from fastapi import Depends, FastAPI
from scalekit.frameworks.fastapi import ScalekitAuth
app = FastAPI()
auth = ScalekitAuth(
env_url=os.environ["SCALEKIT_ENVIRONMENT_URL"],
client_id=os.environ["SCALEKIT_CLIENT_ID"],
client_secret=os.environ["SCALEKIT_CLIENT_SECRET"],
redirect_uri=os.environ["REDIRECT_URI"],
cookie_encryption_secret=os.environ["COOKIE_ENCRYPTION_SECRET"],
cookie_secure=False, # set True behind HTTPS
)
auth.install(app)
@app.get("/account")
async def account(user: dict = Depends(auth.requires_auth)):
return {"sub": user["sub"]}

Open http://localhost:5001/account. A missing session returns 302 to /login, not a JSON 401.

user is access-token claims. sub is always present. email appears only when you add it as a custom access-token claim.

classScalekitAuthhttps://github.com/scalekit-inc/scalekit-sdk-python/blob/main/scalekit/frameworks/fastapi.py
#__init__

Creates the FastAPI session helper. Call install(app) after construction to register routes and the 302 handler.

paramclientScalekitClient | None

Existing client. When omitted, the constructor builds one from env_url, client_id, and client_secret.

optional
paramenv_urlstr

Scalekit environment URL.

required if client is omitted
paramclient_idstr

Application client ID.

required if client is omitted
paramclient_secretstr

Application client secret.

required if client is omitted
paramredirect_uristr

Exact Redirect URI registered in the dashboard.

paramcookie_encryption_secretstr

Secret used to encrypt sk_session. Generate with openssl rand -base64 32.

paramcookie_namestr

Session cookie name.

optional, default sk_session
paramcookie_securebool

Set False for local HTTP.

optional, default True
paramlogin_pathstr

Login route path.

optional, default /login
paramcallback_pathstr

Callback route path.

optional, default /callback
paramlogout_pathstr

Logout route path.

optional, default /logout
parampost_login_redirectstr

Fallback path after login when returnTo is absent.

optional, default /
parampost_logout_redirect_uristr | None

Where logout lands. Defaults to post_login_redirect.

optional
paramfull_logoutbool

When True, logout ends the Scalekit session with id_token_hint.

optional, default True
returnsScalekitAuth

Helper with install, requires_auth, and get_session.

auth = ScalekitAuth(
env_url=os.environ["SCALEKIT_ENVIRONMENT_URL"],
client_id=os.environ["SCALEKIT_CLIENT_ID"],
client_secret=os.environ["SCALEKIT_CLIENT_SECRET"],
redirect_uri=os.environ["REDIRECT_URI"],
cookie_encryption_secret=os.environ["COOKIE_ENCRYPTION_SECRET"],
)
auth.install(app)
classScalekitAuthhttps://github.com/scalekit-inc/scalekit-sdk-python/blob/main/scalekit/frameworks/fastapi.py
#install

Mounts the login, callback, and logout routes and registers the exception handler that turns a missing session into a 302.

Call this once. app.include_router(auth.router) alone skips the 302 handler.

paramappFastAPI

FastAPI application.

returnsNone

Routes and the redirect handler are registered in place.

auth.install(app)
classScalekitAuthhttps://github.com/scalekit-inc/scalekit-sdk-python/blob/main/scalekit/frameworks/fastapi.py
#asyncrequires_auth

FastAPI dependency. Use user: dict = Depends(auth.requires_auth). Session check and refresh run in a thread pool so they do not block the event loop.

paramrequestRequest

Incoming request. Injected by FastAPI.

paramresponseResponse

Injected response. Receives a refreshed sk_session cookie when needed.

returnsdict | None

Access-token claims. Missing session raises an internal error that install converts to 302, not HTTPException(401).

@app.get("/billing")
async def billing(user: dict = Depends(auth.requires_auth)):
return {"sub": user["sub"]}
classScalekitAuthhttps://github.com/scalekit-inc/scalekit-sdk-python/blob/main/scalekit/frameworks/fastapi.py
#get_session

Read-only session lookup. Does not refresh or write a cookie. Only requires_auth refreshes the session.

paramrequestRequest

Incoming request.

returnsdict | None

{"user": ..., "expires_at": ...}, or None. Never includes access_token, refresh_token, or id_token.

session = auth.get_session(request)
if session:
print(session["user"]["sub"], session["expires_at"])