Add Keycloak login to a FastAPI app
Validate Keycloak access tokens in FastAPI with PyJWT and JWKS, add browser login with Authlib, and log users out of Keycloak.
This guide protects a FastAPI endpoint with Keycloak access tokens, adds browser login with Authlib, and logs users out of Keycloak.
Written against FastAPI 0.165.0, Authlib 1.9.10, PyJWT 2.15.1, Starlette 1.10.0 and itsdangerous 2.2.0 on Python 3.13 and Keycloak 26.8, checked on 25 November 2026.
Replace auth.example.com with your RealmDeploy hostname and acme with your realm.
Create the client in Keycloak
In your realm, open Clients and choose Create client. Use these values, then choose Save:
| Setting | Value |
|---|---|
| Client type | OpenID Connect |
| Client ID | my-app |
| Client authentication | On |
| Authentication flow | Standard flow only. Turn Direct access grants off. |
| Root URL | http://localhost:8000 |
| Valid redirect URIs | http://localhost:8000/auth/callback |
| Valid post logout redirect URIs | http://localhost:8000/ |
| Web origins | Leave empty. The browser never calls Keycloak from JavaScript in this app. |
Copy the Client secret from the client's Credentials tab.
For production, add the same paths on your app's HTTPS address, for example https://app.example.com/auth/callback and https://app.example.com/. Keycloak compares redirect URIs exactly.
If you only need the API part, you still need a client that requests the tokens; the API itself needs no client of its own.
Environment variables
OIDC_ISSUER=https://auth.example.com/realms/acme
OIDC_CLIENT_ID=my-app
OIDC_CLIENT_SECRET=paste-the-client-secret
API_AUDIENCE=my-api
SESSION_SECRET=a-long-random-stringMake SESSION_SECRET with python -c "import secrets; print(secrets.token_urlsafe(32))". It signs the session cookie.
Install
python -m pip install "fastapi[standard]" authlib itsdangerous "pyjwt[crypto]"fastapi[standard] brings Uvicorn and httpx2, which Authlib's Starlette client uses since Authlib 1.8. Starlette's SessionMiddleware needs itsdangerous. PyJWT needs the crypto extra for RS256.
Add login
import os
from html import escape
from typing import Annotated
import jwt
from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from starlette.middleware.sessions import SessionMiddleware
ISSUER = os.environ["OIDC_ISSUER"]
API_AUDIENCE = os.environ["API_AUDIENCE"]
app = FastAPI()
# Holds the login state and, after login, the user and ID token.
# Starlette signs this cookie but does not encrypt it.
app.add_middleware(SessionMiddleware, secret_key=os.environ["SESSION_SECRET"])
oauth = OAuth()
oauth.register(
name="keycloak",
client_id=os.environ["OIDC_CLIENT_ID"],
client_secret=os.environ["OIDC_CLIENT_SECRET"],
server_metadata_url=f"{ISSUER}/.well-known/openid-configuration",
client_kwargs={"scope": "openid profile email"},
)
@app.get("/")
async def home(request: Request):
user = request.session.get("user")
if not user:
return HTMLResponse('<a href="/login">Log in</a>')
name = escape(user["preferred_username"] or user["sub"])
return HTMLResponse(f'<p>Signed in as {name}</p><a href="/logout">Log out</a>')
@app.get("/login")
async def login(request: Request):
redirect_uri = request.url_for("auth_callback")
return await oauth.keycloak.authorize_redirect(request, redirect_uri)
@app.get("/auth/callback")
async def auth_callback(request: Request):
try:
token = await oauth.keycloak.authorize_access_token(request)
except OAuthError as exc:
raise HTTPException(status_code=400, detail=exc.error)
userinfo = token["userinfo"] # claims of the verified ID token
request.session["user"] = {
"sub": userinfo["sub"],
"preferred_username": userinfo.get("preferred_username"),
"email": userinfo.get("email"),
}
request.session["id_token"] = token["id_token"] # needed to log out
return RedirectResponse("/")Start it with the variables from .env:
uvicorn main:app --env-file .env --reloadOpen http://localhost:8000 (not 127.0.0.1, see Common errors) and choose Log in.
Authlib reads the realm's discovery document, sends the browser to Keycloak with a state and a nonce, and in the callback exchanges the code, then checks the ID token's signature, issuer, audience, expiry and nonce. token["userinfo"] holds the verified ID token's claims.
Protect an API
Add an Audience mapper
By default, Keycloak access tokens carry aud: account, and only when the user has roles of the account client. Add your API's audience to the tokens of the client that calls it, here my-app:
- Open Clients, then
my-app, then the Client scopes tab, thenmy-app-dedicated. - Choose Configure a new mapper, then Audience. If the scope already has mappers, choose Add mapper, By configuration, Audience.
- Set Name to
my-api audience, Included Custom Audience tomy-api, Add to access token on and Add to ID token off. Choose Save.
If your API has its own client in Keycloak, choose it under Included Client Audience instead, and set API_AUDIENCE to its client ID.
To check, open the client's Client scopes tab, then the Evaluate sub-tab, pick a user and look at Generated access token: aud should contain my-api.
Validate the token in a dependency
Add this to main.py:
bearer = HTTPBearer()
# Downloads the realm's public keys on first use and caches them.
jwks_client = jwt.PyJWKClient(f"{ISSUER}/protocol/openid-connect/certs")
def verify_token(
credentials: Annotated[HTTPAuthorizationCredentials, Depends(bearer)],
) -> dict:
token = credentials.credentials
try:
signing_key = jwks_client.get_signing_key_from_jwt(token)
return jwt.decode(
token,
signing_key,
algorithms=["RS256"],
audience=API_AUDIENCE,
issuer=ISSUER,
options={"require": ["exp", "iss", "aud", "sub"]},
)
except jwt.PyJWTError as exc:
raise HTTPException(
status_code=401,
detail=f"Invalid token: {exc}",
headers={"WWW-Authenticate": "Bearer"},
)
@app.get("/api/me")
def api_me(claims: Annotated[dict, Depends(verify_token)]):
return {"sub": claims["sub"], "username": claims.get("preferred_username")}PyJWKClient picks the key by the token's kid and fetches the key set again when it meets a new kid, so Keycloak key rotation needs no restart. algorithms=["RS256"] is fixed in code, never read from the token. verify_token is a plain def, so FastAPI runs it in a thread pool and the occasional key download does not block the event loop.
A caller sends a user's access token issued to my-app:
curl -i -H "Authorization: Bearer $ACCESS_TOKEN" http://localhost:8000/api/meWithout a token, HTTPBearer answers 401 Not authenticated.
Log out
Clearing the session ends only your app's login. The Keycloak session stays, so the next Log in signs the user straight back in. Send the browser to Keycloak's end-session endpoint too. Authlib reads it from the discovery document:
@app.get("/logout")
async def logout(request: Request):
id_token = request.session.pop("id_token", None)
request.session.clear()
return await oauth.keycloak.logout_redirect(
request,
post_logout_redirect_uri=str(request.url_for("home")),
id_token_hint=id_token,
client_id=oauth.keycloak.client_id,
)The redirect looks like https://auth.example.com/realms/acme/protocol/openid-connect/logout?id_token_hint=...&post_logout_redirect_uri=http%3A%2F%2Flocalhost%3A8000%2F&state=...&client_id=my-app. Keycloak ends its session and returns the browser to http://localhost:8000/, which must be listed in Valid post logout redirect URIs. With id_token_hint, Keycloak does not ask the user to confirm; client_id lets the redirect work even when the session no longer holds an ID token. The logout URL builder builds and checks the same URL.
Authlib adds a state and keeps it in the session. To check it when the browser comes back, point post_logout_redirect_uri at a route that calls await oauth.keycloak.validate_logout_response(request).
Common errors
| Error | Cause | Fix |
|---|---|---|
| Keycloak shows Invalid parameter: redirect_uri | The callback URL is built from the request, so 127.0.0.1 and localhost differ, and so do http and https. | Open the app on the host you registered. Compare both URLs with the redirect URI matcher. |
400 mismatching_state in the callback | The session cookie set at /login did not come back: another host name (127.0.0.1 against localhost), a changed SESSION_SECRET, or a blocked cookie. | Use one host name throughout and keep the secret stable. |
The callback uses http:// in production | Uvicorn runs behind a TLS proxy whose forwarded headers it does not trust. By default it trusts them only from 127.0.0.1 and ::1. | Start Uvicorn with --forwarded-allow-ips set to your proxy's address. |
| Keycloak shows Invalid redirect uri after logout | post_logout_redirect_uri is not in Valid post logout redirect URIs. | Add http://localhost:8000/ (or your production URL) exactly. |
401 Invalid token: Audience doesn't match | The access token has no my-api in aud. | Add the Audience mapper. Check the token with the JWT decoder. |
401 Invalid token: Invalid issuer | OIDC_ISSUER differs from the token's iss: another hostname, realm or scheme. | Copy issuer from the discovery document, for example with the OIDC discovery viewer. |
401 Invalid token: Signature has expired | Keycloak access tokens live 5 minutes by default. | The caller refreshes the token and retries. |
401 Invalid token: Unable to find a signing key that matches | The token comes from another realm or server. | Compare its kid with the realm's keys using the JWT kid matcher. |
AuthlibDeprecationWarning: The httpx module is deprecated; please use httpx2 instead. | httpx2 is not installed. | Install fastapi[standard] or httpx2. |
FAQ
Can I use the access token from the browser login to call the API?
Yes. token["access_token"] in the callback is an access token for my-app, with my-api in aud once the Audience mapper is in place. This sample does not keep it; store it server-side if your app calls the API for the user.
Why does the session cookie hold the ID token?
Logout needs it as id_token_hint. Starlette's session cookie is signed, not encrypted, so the user can read what is in it, which is their own ID token and profile. Keep it small, and do not put other secrets in it.
Why validate locally instead of calling userinfo or introspection?
Local validation needs no network call per request once the keys are cached, and it checks the audience, so only tokens meant for your API get in. Introspection is the choice when you must notice revoked tokens before they expire.
Do I need to ask you to open an outgoing connection?
No. Every call in this guide goes from your app to Keycloak: discovery, token and JWKS. Logout is a browser redirect, so Keycloak never calls your app.
Sources
Add Keycloak login to a Django app
Add Keycloak login to Django with mozilla-django-oidc, log users out of Keycloak too, and protect a REST API by validating access tokens with PyJWT.
Add Keycloak login to a Go app
Sign users in to a Go web app with Keycloak using go-oidc and x/oauth2, verify access tokens in API middleware, and log users out.