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.
Before you begin
Section titled “Before you begin”- Python 3.10 or later.
- A confidential client on your issuer with
client_secret_basic, the redirect URIhttp://localhost:8000/callback, the post-logout redirect URIhttp://localhost:8000/, and a minted secret. See Register a client.
Create the project
Section titled “Create the project”mkdir authwise-fastapi && cd authwise-fastapipython3 -m venv .venv.venv/bin/pip install fastapi uvicorn authlib itsdangerous httpxThis 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.
Write the application
Section titled “Write the application”Create main.py:
import os, timefrom urllib.parse import urlencode
from authlib.integrations.starlette_client import OAuthfrom fastapi import FastAPI, Requestfrom fastapi.responses import HTMLResponse, RedirectResponsefrom 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:
/logincallsauthorize_redirect. Authlib creates the PKCE verifier,state, andnonce, keeps them in the session, and redirects to the issuer it discovered from the metadata URL./callbackcallsauthorize_access_token, which checksstate, exchanges the code with the secret, fetches the issuer’s keys, and validates the ID token’s signature,iss,aud,exp, andnonce. The claims come back astoken["userinfo"], andsubis the person’s stable ID./refreshexchanges 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./logoutclears the session and sends the browser to the issuer’s end-session endpoint, which ends the issuer session and returns to/.
Run it
Section titled “Run it”export AUTHWISE_ISSUER=https://login.example.comexport AUTHWISE_CLIENT_ID=CLIENT_IDexport AUTHWISE_CLIENT_SECRET="$(cat client-secret.txt)"export SESSION_SECRET="$(openssl rand -hex 32)".venv/bin/uvicorn main:app --port 8000Replace 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.
Good to know
Section titled “Good to know”SessionMiddlewareis required. Authlib keepsstate,nonce, and the PKCE verifier in the session between/loginand/callback, so both URLs must share the same host and port.code_challenge_method: "S256"inclient_kwargsturns 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_tokenhas already verified the token and returns its claims. token["userinfo"]is aUserInfoobject. Convert it withdict()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_SECRETstable across restarts, or every session ends with each deployment.
What’s next
Section titled “What’s next”- Send
access_tokenas 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.