Skip to main content

Sign-in for a FastAPI app

Add login, callback and logout routes to a FastAPI app, and read the signed-in person in a dependency.

RecipeReadyView source
Packages
lumoauth
Works with
PythonFastAPI

What it shows​

  1. lumo_auth_router() adds the routes /auth/login, /auth/callback and /auth/logout to the app.
  2. /auth/login goes to the hosted sign-in page. The callback exchanges the code and stores the tokens and the profile in the session.
  3. The dependency get_current_user returns the signed-in person, or None. A page that needs a person redirects to /auth/login.
  4. require_auth() protects an API route: it answers 401 without a session, and 403 when a scope is missing.
  5. The route /signout of the app clears the session and ends the session at LumoAuth. A small guard keeps other sites from signing the person out.

Before you start​

  • Python 3.10 or later.
  • An API key with the scopes admin:clients:read and admin:clients:write. Create it in the portal under Applications & developer tools, API keys.
  • A confidential application with the redirect URI http://localhost:8000/auth/callback. The setup script creates it.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYAn API key with the scopes admin:clients:read and admin:clients:write. Only the setup script uses it.
APP_URLOptional. The address of your app, when it is not http://localhost:8000. The setup script and the app read it.
LUMOAUTH_CLIENT_IDThe client ID of the application. The setup script prints it.
LUMOAUTH_CLIENT_SECRETThe client secret of the application. The setup script prints it.
SESSION_SECRETThe session middleware signs its cookie with this value. The setup script prints a random value.

The setup script creates the application through the Admin API and prints the variables of the app. LumoAuth shows a client secret only once, so each run makes a new secret.

node sign-in/fastapi/setup.mjs
setup.mjs
// Creates the application that the FastAPI app signs in with: a confidential
// application with the callback address of the app. Run it again at any time.
//
// node sign-in/fastapi/setup.mjs
//
// The API key needs the scopes admin:clients:read and admin:clients:write.
// APP_URL is the address of your app. The default is http://localhost:8000.
import { randomBytes } from 'node:crypto';
import { call, list, printEnv } from '../../_lib/admin.mjs';

const appUrl = (process.env.APP_URL ?? 'http://localhost:8000').replace(/\/+$/, '');
const name = 'FastAPI sign-in';
const redirectUris = [`${appUrl}/auth/callback`];

let secret;
let client = (await list('/admin/clients')).find((c) => c.name === name);
if (client) {
// LumoAuth shows a client secret only once, so a second run makes a new one.
await call('PATCH', `/admin/clients/${client.id}`, { redirectUris });
secret = (await call('POST', `/admin/clients/${client.id}/rotate-secret`)).data.secret;
} else {
client = (await call('POST', '/admin/clients', { name, redirectUris, isConfidential: true })).data;
secret = client.secret;
}

console.log(`Application "${name}" is ready. Its redirect URI is ${redirectUris[0]}.`);
printEnv({
LUMOAUTH_CLIENT_ID: client.clientId,
LUMOAUTH_CLIENT_SECRET: secret,
// The session middleware signs its cookie with this value.
SESSION_SECRET: randomBytes(32).toString('hex'),
});

Copy the export lines that the script prints into the terminal where you start the app.

Sign-out returns to your app only when the address is registered. The Admin API has no field for it, so add it in the portal:

  1. Open Applications and select FastAPI sign-in.
  2. Open the Configuration tab and go to the section Logout.
  3. Under Post-logout redirect URIs, enter http://localhost:8000/.
  4. Select Save configuration.

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. A browser signed in and out through the hosted page. A link and a form on another site did not sign the person out.

sign-in/fastapi/python/main.py
"""A FastAPI app with sign-in: the hosted sign-in page, a session, a protected
page, a protected API route and sign-out.

python sign-in/fastapi/python/main.py
"""
import os
from urllib.parse import urlencode, urlsplit

import uvicorn
from fastapi import Depends, FastAPI, Request
from fastapi.responses import HTMLResponse, PlainTextResponse, RedirectResponse
from starlette.middleware.sessions import SessionMiddleware

from lumoauth.fastapi import User, get_current_user, lumo_auth_router, require_auth

APP_URL = os.environ.get("APP_URL", "http://localhost:8000").rstrip("/")
LUMOAUTH_URL = os.environ.get("LUMOAUTH_URL", "https://app.lumoauth.dev").rstrip("/")
ORG_ID = os.environ["LUMOAUTH_ORG_ID"]

app = FastAPI()

# The router keeps its data in the session of Starlette. Add the session
# middleware, or /auth/login answers 500.
app.add_middleware(
SessionMiddleware,
secret_key=os.environ["SESSION_SECRET"],
https_only=APP_URL.startswith("https:"),
)


# Another site must not be able to sign a person out. This guard covers
# /signout and /auth/logout of the router. A GET signs out at once only when
# the browser says that it comes from this app or from a typed address. Any
# other GET gets a page with a button, and a POST must come from this app.
@app.middleware("http")
async def sign_out_guard(request: Request, call_next):
if request.url.path not in ("/signout", "/auth/logout"):
return await call_next(request)
site, origin = request.headers.get("sec-fetch-site"), request.headers.get("origin")
if request.method == "POST":
if (origin == APP_URL) if origin not in (None, "null") else (site == "same-origin"):
return await call_next(request)
return PlainTextResponse("Sign-out refused: the request did not come from this app.", status_code=403)
if site in ("same-origin", "none"):
return await call_next(request)
return HTMLResponse(
'<p>Do you want to sign out?</p><form method="post"><button>Sign out</button></form>',
headers={
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "same-origin",
# No form-action: Chromium applies it to the redirect to LumoAuth too.
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
},
)


# Adds /auth/login, /auth/callback and /auth/logout.
app.include_router(
lumo_auth_router(
base_url=LUMOAUTH_URL,
organization=ORG_ID,
client_id=os.environ["LUMOAUTH_CLIENT_ID"],
client_secret=os.environ["LUMOAUTH_CLIENT_SECRET"],
callback_path="/auth/callback",
),
prefix="/auth",
)


# A public page. get_current_user returns the signed-in person, or None.
@app.get("/", response_class=HTMLResponse)
def home(user: User | None = Depends(get_current_user)):
if user is None:
return '<p>Nobody is signed in.</p><a href="/auth/login">Sign in</a>'
return (
f"<p>Signed in as {user.email}.</p>"
'<p><a href="/dashboard">Dashboard</a> · <a href="/api/me">Profile as JSON</a>'
' · <a href="/signout">Sign out</a></p>'
)


# A protected page: a signed-out visitor goes to sign-in and comes back here.
@app.get("/dashboard", response_class=HTMLResponse)
def dashboard(user: User | None = Depends(get_current_user)):
if user is None:
return RedirectResponse("/auth/login?return_to=/dashboard", status_code=302)
return f'<h1>Dashboard</h1><p>User ID: {user.sub}</p><a href="/">Home</a>'


# A protected API route: require_auth() answers 401 without a session.
@app.get("/api/me")
def me(user: User = Depends(require_auth())):
return {"sub": user.sub, "email": user.email, "name": user.name}


# require_auth() can also ask for scopes of the token: 403 when one is missing.
@app.get("/api/email")
def email(user: User = Depends(require_auth(scopes=["email"]))):
return {"email": user.email}


# /auth/logout of the router clears only the session of this app. This route
# also ends the session at LumoAuth: it sends the browser to the logout
# endpoint with the ID token, and LumoAuth sends it back to the home page.
# The button on the confirmation page of sign_out_guard sends a POST.
@app.api_route("/signout", methods=["GET", "POST"])
def sign_out(request: Request):
# The router keeps its data under the key "__lumoauth" of the session.
tokens = request.session.pop("__lumoauth", {}).get("tokens", {})
if not tokens.get("id_token"):
return RedirectResponse("/", status_code=302)
query = urlencode({"id_token_hint": tokens["id_token"], "post_logout_redirect_uri": f"{APP_URL}/"})
return RedirectResponse(f"{LUMOAUTH_URL}/orgs/{ORG_ID}/api/v1/oauth/logout?{query}", status_code=302)


if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=urlsplit(APP_URL).port or 8000)
python sign-in/fastapi/python/main.py

Check the result​

Open http://localhost:8000 in a browser, select Sign in, and sign in as a user of your organization.

Output
Signed out
GET / 200 Nobody is signed in.
GET /dashboard 302 /auth/login?return_to=/dashboard
GET /api/me 401 {"detail":{"error":"unauthenticated"}}

Signed in
GET / 200 Signed in as maya.chen@example.com.
GET /dashboard 200 User ID: 0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10
GET /api/me 200 {"sub":"0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10","email":"maya.chen@example.com","name":"Maya Chen"}
  • The browser holds the cookie session of Starlette, marked httpOnly. Local storage and session storage hold no token.
  • Sign out returns to /, and the next visit to /dashboard shows the sign-in page again.
  • A link to /signout on another site shows a page with the question "Do you want to sign out?". The person stays signed in until they select Sign out. A form on another site that posts to the route gets 403. The guard of the recipe covers /signout and /auth/logout.

Limits​

  • /auth/logout of the router clears only the session of the app. The person stays signed in at LumoAuth, and the next /auth/login returns without a sign-in page. The route /signout of this recipe therefore calls the logout endpoint itself.
  • The session middleware of Starlette keeps the whole session in the cookie. The cookie is signed, not encrypted, and it holds the tokens. It was about 3,200 characters long in the test, and a browser refuses a cookie that is longer than about 4,000. For more scopes or claims, use a session middleware that stores the data on the server.
  • The router does not refresh the access token. The session lasts as long as the cookie of the session middleware.
  • require_auth() answers with a status code. It does not redirect, so a page route sends the visitor to /auth/login itself.
  • The scopes argument reads the scopes of the token in the session. It does not check roles or permissions.