Protecting a Python API with Keycloak: Check the JWT Signature, Issuer and Expiry in FastAPI, Django and Flask
Keycloak signs the access token; your API only checks it. Run Keycloak in Docker with a realm file, fetch its public keys once, check RS256, the issuer and the expiry, and protect /api/me with one Depends. Then the same check as a Django REST framework class and a Flask decorator.
What you will learn
- Run Keycloak in Docker with a realm, a public front end client and a healthcheck
- Read the three parts of a Keycloak access token
- Verify a token against Keycloak's JWKS with RS256, the issuer and the expiry
- Protect a route with Depends in FastAPI, an authentication class in Django REST framework, or a decorator in Flask
Before you start
- A layered FastAPI project
- Docker Compose basics
So far anyone can call the backend. There's no login at all. Keycloak will handle sign up and login, and the backend will check a token on every protected call.
Here's the idea in one picture. The user signs in at Keycloak, not at the backend. Keycloak gives the browser a signed access token. The browser sends that token on every API call in the Authorization header as a Bearer token. The backend has one job: check the token, and answer only if it's good. The password never reaches the backend.
Keycloak in Docker
An AI coding agent added the pieces from one prompt: a Dockerfile and Compose support for the backend, Keycloak JWT validation with Bearer protection, one test route GET /api/me, and a realm with a client for the React front end, with login and sign up turned on. It added docker-compose.yml, a keycloak folder with realm-subly.json, and app/auth/keycloak.py. Here's the Keycloak service:
services:
keycloak:
image: quay.io/keycloak/keycloak:26.0
container_name: subly-keycloak
command: ["start-dev", "--import-realm"]
environment:
KC_BOOTSTRAP_ADMIN_USERNAME: admin
KC_BOOTSTRAP_ADMIN_PASSWORD: admin
KC_HOSTNAME: localhost
KC_HOSTNAME_STRICT: "false"
KC_HTTP_ENABLED: "true"
ports:
- "8080:8080"
volumes:
- ./keycloak/realm-subly.json:/opt/keycloak/data/import/realm-subly.json:ro
start-dev is development mode on plain HTTP, and --import-realm loads the realm file at start. The admin/admin login is a dev-only value for a local container; never put a real password in a file like this. KC_HOSTNAME is localhost, so every token says it was issued by localhost, port 8080. A healthcheck asks for the realm's OpenID configuration every 10 seconds.
The backend service gets two Keycloak addresses:
backend:
build: ./backend
environment:
KEYCLOAK_INTERNAL_URL: http://keycloak:8080
KEYCLOAK_ISSUER: http://localhost:8080/realms/subly
KEYCLOAK_REALM: subly
CORS_ORIGINS: http://localhost:3000
depends_on:
keycloak:
condition: service_healthy
Inside Docker, containers find each other by service name, so http://keycloak:8080 is how the backend reaches Keycloak to fetch its keys. The issuer is the address the browser uses, so it's the one written inside every token. One Keycloak, two addresses: one to reach it, one to compare against.
The realm file
The realm is subly. Registration is allowed, the email is the username, remember me is on, and sslRequired is none (fine on localhost, not on a real server). The access token lifespan is 1800 seconds, thirty minutes. There's one client, subly-frontend. It's a public client because a browser app can't keep a secret, its redirect address is localhost port 3000, and it uses PKCE with S256, which protects the login code on its way back to the browser.
The first run finds a bug
docker compose up --build starts Keycloak, and its realm address answers 200. But the healthcheck keeps failing, so Docker marks Keycloak unhealthy, and the backend, which waits for a healthy Keycloak, is created but never starts. For now the backend starts on its own with docker compose up -d --no-deps backend. This is why you always test what an agent builds. The fix comes in finishing the Keycloak starter kit.
What's inside the token
A JWT is three parts joined by dots. The header says the algorithm, RS256, and the type, JWT. The payload holds the claims: who issued it, who it's about, which client asked, the username, the roles and when it stops working. The signature is made by Keycloak with its private key. The API checks it with Keycloak's public key. Anyone can read the payload, but nobody can change it without breaking the signature.
The check in FastAPI
bearer_scheme = HTTPBearer(auto_error=True)
_jwks_cache: dict | None = None
def _jwks_url() -> str:
return (
f"{settings.keycloak_internal_url}"
f"/realms/{settings.keycloak_realm}"
f"/protocol/openid-connect/certs"
)
def get_jwks() -> dict:
"""Fetch and cache Keycloak's signing keys (JWKS)."""
global _jwks_cache
if _jwks_cache is None:
try:
response = httpx.get(_jwks_url(), timeout=5.0)
response.raise_for_status()
_jwks_cache = response.json()
except httpx.HTTPError as exc:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=f"Could not fetch Keycloak JWKS: {exc}",
) from exc
return _jwks_cache
def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
) -> dict[str, Any]:
token = credentials.credentials
try:
payload = jwt.decode(
token,
get_jwks(),
algorithms=["RS256"],
issuer=settings.keycloak_issuer,
options={"verify_aud": False},
)
except JWTError as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Invalid or expired token: {exc}",
headers={"WWW-Authenticate": "Bearer"},
) from exc
return payload
HTTPBearerreads theAuthorizationheader and takes the token after "Bearer". A missing header stops the request with a 401.- JWKS means JSON Web Key Set: Keycloak's public keys on the realm's certs address, reached on the internal address.
get_jwksfetches them once with httpx and keeps them in a module variable. If Keycloak can't be reached, the answer is 503. jwt.decodefrom python-jose checks the signature. The algorithm must be RS256, so a token signed any other way is rejected. The issuer must match, so a token from another realm or server fails. jose also checks the expiry by default. The audience check is switched off to keep things simple.
Protecting a route is one parameter:
@router.get("", response_model=MeResponse, summary="Current user",
operation_id="get_me")
def get_me(claims: dict[str, Any] = Depends(get_current_user)) -> MeResponse:
return MeResponse(
sub=claims.get("sub", ""),
username=claims.get("preferred_username"),
email=claims.get("email"),
name=claims.get("name"),
given_name=claims.get("given_name"),
family_name=claims.get("family_name"),
email_verified=claims.get("email_verified"),
roles=claims.get("realm_access", {}).get("roles", []),
)
Before get_me runs, FastAPI runs HTTPBearer, then get_current_user. If either fails, get_me never runs. The roles come from realm_access.roles; this route only returns them, it doesn't check any role yet.
Test it five ways
| Request | Answer |
|---|---|
/api/v1/hello, no token | 200, hello world (still open) |
/api/me, no header | 401, Not authenticated |
Bearer abc | 401, Not enough segments |
| Valid token with one extra character | 401, Signature verification failed |
| Valid token | 200, the test user's details and roles |
The test user's roles were offline_access, default-roles-subly and uma_authorization, which every new user in the realm gets by default. In Swagger there's now an Authorize button and a lock on /api/me, because the route uses HTTPBearer.
The same check in Django
In Django REST framework the protection is set once, in settings.py:
REST_FRAMEWORK = {
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
"DEFAULT_AUTHENTICATION_CLASSES": [
"myapp.auth.KeycloakAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticated",
],
}
So every view needs a valid token unless it says otherwise. The hello view opts out with an empty authentication_classes list and AllowAny. The class itself has one method, authenticate:
def authenticate(self, request):
auth = authentication.get_authorization_header(request).split()
if not auth or auth[0].lower() != self.keyword.lower().encode():
return None
if len(auth) != 2:
raise exceptions.AuthenticationFailed("Invalid Authorization header.")
token = auth[1].decode()
claims = self._validate(token)
No Bearer header returns None, and IsAuthenticated turns that into a 401. A good token returns a KeycloakUser built from the claims, and that's what request.user holds in the view. _validate uses PyJWT, not python-jose. It reads the token's header without trusting it, takes the key ID, picks the matching key from a cache that keeps the keys for 600 seconds (and refetches once when a key ID isn't known), and calls jwt.decode with the issuer.
algorithms=[header.get("alg", "RS256")]. The key still comes only from Keycloak, but pinning RS256, as the FastAPI version does, is safer. And if Keycloak can't be reached, Django answers 401 where FastAPI answers 503.The answers match FastAPI's in status: 401 saying the credentials are missing for no header, "Malformed token" for Bearer abc, "Signature verification failed" for a changed token, 200 for a good one. Swagger has no Authorize button here, because the class doesn't describe itself to the schema.
The same check in Flask
Flask uses a decorator and Flask's g object instead of a parameter:
def require_auth(fn: Callable[..., Any]) -> Callable[..., Any]:
@wraps(fn)
def wrapper(*args: Any, **kwargs: Any) -> Any:
token = _extract_bearer_token()
if not token:
abort(401, message="Missing Bearer token")
try:
claims = keycloak_service.decode(token)
except jwt.ExpiredSignatureError:
abort(401, message="Token expired")
except jwt.InvalidTokenError as e:
abort(401, message=f"Invalid token: {e}")
except Exception as e:
abort(401, message=f"Token validation failed: {e}")
g.user = claims
return fn(*args, **kwargs)
return wrapper
The key work sits in a KeycloakService class. It creates a PyJWT PyJWKClient once, but first tries the certs address up to 30 times, two seconds apart, in case Keycloak is still starting. decode asks the client for the key that signed this token and calls jwt.decode with RS256 and the issuer. In this project the hello route also has require_auth, so in Flask it's protected too, and the error JSON has code, message and status where FastAPI gave detail.
Common mistakes
- Comparing the issuer with the internal Docker address. The token carries the address the browser used.
- Fetching the JWKS on every request. Cache it, and refetch only for an unknown key ID.
- Trusting the algorithm the token names. Pin RS256.
- Copying
sslRequired: noneand admin/admin into a real deployment.
Quick recap
| FastAPI | Django | Flask | |
|---|---|---|---|
| Reads the header | HTTPBearer | authenticate splits it | _extract_bearer_token |
| Library | python-jose | PyJWT | PyJWT PyJWKClient |
| Protects a route | Depends(get_current_user) | Default in settings, opt out with AllowAny | @require_auth |
| Claims live on | A parameter | request.user | g.user |
Try it yourself
Add a second protected route that returns only the username, and test it with no token, a broken token and a good one.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
Follow GET / through the FastAPI blog to two SQL statements and an HTML page, then a login: one SELECT, a bcrypt check, a 303 with a signed session cookie that decodes to user_id 1. A changed cookie gets 401, a plain user 403, and three slow requests on async def with a blocking session finish at 1.92 s while a ping waits 1.83 s.
An Auth Starter Kit with Keycloak: Build Sign In Once, Put the Backend Between React and the Identity Provider
Almost every project needs sign in, sign out and a token check, so build them once in a starter kit. Tour the kit's four pillars, then finish it: a fix prompt, a backend that sits between React and Keycloak with register, login, me and logout routes, and the limits of a stateless access token.
How an Identity Provider Login Works: The OpenID Connect Code Flow vs a Backend Password Grant, with Keycloak
What an identity provider does, the four Keycloak words you see everywhere, the standard OpenID Connect sign in (redirect, code, token), and the custom-page version where FastAPI sends a password grant. Then one token followed from login to the check, plus refresh, logout and dev mode.
AWS Cognito vs Keycloak: User Pools, App Clients and When a Managed Identity Provider Wins
Cognito is AWS's identity service, Keycloak as a service. Its three pieces (user pool, app client, hosted UI), the tokens it issues, a side-by-side with Keycloak on running costs and lock-in, and why the rest of the subtitle app doesn't change when the door is swapped.
