Skip to content

Quickstart: Python with FastAPI

This page gets a FastAPI application signing people in through your issuer with Authlib: authorization code with PKCE, a cookie session, a refresh, and sign-out. It applies Sign users in with OpenID Connect and takes about ten minutes.

  • Python 3.10 or later.
  • A confidential client on your issuer with client_secret_basic, the redirect URI http://localhost:8000/callback, the post-logout redirect URI http://localhost:8000/, and a minted secret. See Register a client.
Terminal window
mkdir authwise-fastapi && cd authwise-fastapi
python3 -m venv .venv
.venv/bin/pip install fastapi uvicorn authlib itsdangerous httpx

This page was verified with FastAPI 0.162, Authlib 1.9, and uvicorn 0.54. itsdangerous signs the session cookie, and httpx is the HTTP client Authlib uses.

Create main.py:

import os, time
from urllib.parse import urlencode
from authlib.integrations.starlette_client import OAuth
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from starlette.middleware.sessions import SessionMiddleware
app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key=os.environ["SESSION_SECRET"])
oauth = OAuth()
oauth.register(
name="authwise",
server_metadata_url=f"{os.environ['AUTHWISE_ISSUER']}/.well-known/openid-configuration",
client_id=os.environ["AUTHWISE_CLIENT_ID"],
client_secret=os.environ["AUTHWISE_CLIENT_SECRET"],
client_kwargs={"scope": "openid profile email offline_access", "code_challenge_method": "S256"},
)
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
user = request.session.get("user")
if not user:
return '<a href="/login">Sign in</a>'
return f'Signed in as {user["sub"]} ({user.get("email")}) <a href="/refresh">refresh</a> <a href="/logout">logout</a>'
@app.get("/login")
async def login(request: Request):
return await oauth.authwise.authorize_redirect(request, request.url_for("callback"))
@app.get("/callback")
async def callback(request: Request):
token = await oauth.authwise.authorize_access_token(request) # verifies state, PKCE, id_token
request.session["user"] = dict(token.pop("userinfo")) # id_token claims: sub, email, name, ...
request.session["token"] = token # access_token, refresh_token, id_token, expires_at
return RedirectResponse("/")
@app.get("/refresh", response_class=HTMLResponse)
async def refresh(request: Request):
token = await oauth.authwise.fetch_access_token(
grant_type="refresh_token", refresh_token=request.session["token"]["refresh_token"]
)
request.session["token"] = dict(token) # refresh tokens rotate: keep the new one
return f'Access token now expires at {time.strftime("%H:%M:%S", time.localtime(token["expires_at"]))} <a href="/">home</a>'
@app.get("/logout")
async def logout(request: Request):
token = request.session.pop("token", None)
request.session.clear()
metadata = await oauth.authwise.load_server_metadata()
params = {"post_logout_redirect_uri": str(request.url_for("home"))}
if token:
params["id_token_hint"] = token["id_token"]
return RedirectResponse(f"{metadata['end_session_endpoint']}?{urlencode(params)}")

What each route does:

  • /login calls authorize_redirect. Authlib creates the PKCE verifier, state, and nonce, keeps them in the session, and redirects to the issuer it discovered from the metadata URL.
  • /callback calls authorize_access_token, which checks state, exchanges the code with the secret, fetches the issuer’s keys, and validates the ID token’s signature, iss, aud, exp, and nonce. The claims come back as token["userinfo"], and sub is the person’s stable ID.
  • /refresh exchanges the refresh token. The result is a complete new token with a new refresh token, and the old one is now refused, so the session stores the whole new token.
  • /logout clears the session and sends the browser to the issuer’s end-session endpoint, which ends the issuer session and returns to /.
Terminal window
export AUTHWISE_ISSUER=https://login.example.com
export AUTHWISE_CLIENT_ID=CLIENT_ID
export AUTHWISE_CLIENT_SECRET="$(cat client-secret.txt)"
export SESSION_SECRET="$(openssl rand -hex 32)"
.venv/bin/uvicorn main:app --port 8000

Replace https://login.example.com with your issuer’s URL and CLIENT_ID with the client’s ID. Open http://localhost:8000/, click Sign in, and sign in on the hosted page. The home page shows Signed in as u-…. refresh shows a later expiry each time, and logout returns you to the sign-in link.

  • SessionMiddleware is required. Authlib keeps state, nonce, and the PKCE verifier in the session between /login and /callback, so both URLs must share the same host and port.
  • code_challenge_method: "S256" in client_kwargs turns PKCE on. The issuer refuses a request without it.
  • Do not decode the ID token yourself or call the userinfo endpoint just for sub. authorize_access_token has already verified the token and returns its claims.
  • token["userinfo"] is a UserInfo object. Convert it with dict() before storing it in the session.
  • The session cookie holds about 3 KB here, under the browser’s 4 KB limit but not by much. A real application keeps the tokens in a server-side store and only a session ID in the cookie.
  • Keep SESSION_SECRET stable across restarts, or every session ends with each deployment.
  • Send access_token as a bearer token to the API the client’s audience names, and validate it there against the issuer’s JWKS.
  • Read Keep the session alive for the refresh token lifetimes and how to tune them.