Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Backend vs Frontend: What Runs Where, and Why the Server Is the One You Trust
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • File Upload and Download in FastAPI: multipart, UploadFile and FileResponse
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
  • A Layered FastAPI Project: Controllers, Services, Schemas and One Folder per Concern
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • An Auth Starter Kit with Keycloak: Build Sign In Once, Put the Backend Between React and the Identity Provider
  • Protecting a Python API with Keycloak: Check the JWT Signature, Issuer and Expiry in FastAPI, Django and Flask
  • How an Identity Provider Login Works: The OpenID Connect Code Flow vs a Backend Password Grant, with Keycloak
  • AWS Cognito vs Keycloak: User Pools, App Clients and When a Managed Identity Provider Wins
  • Migrating FastAPI from Keycloak to AWS Cognito: The Four Values, the JWKS Address and Every Check on an Access Token
  • Testing a Cognito Login End to End: Allow the Password Flow, Confirm the Email Code, and Reset a Forgotten Password
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  • Testing a FastAPI Blog with pytest: a Test Database through dependency_overrides, Login Fixtures and Reading a Failure
  • Smoke-Testing a Dockerized LLM App by Hand: Stage the Weights, Check Every Layer, Make Errors Say Why
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Authentication

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Authentication

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 signs, the API checks Browser Keycloak private key signs FastAPI public key checks 1. sign in, get token 2. Bearer token 3. fetch JWKS once 200 with claims or 401
Keycloak signs the token with its private key. The API checks it with Keycloak's public keys, fetched once.

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
  • HTTPBearer reads the Authorization header 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_jwks fetches them once with httpx and keeps them in a module variable. If Keycloak can't be reached, the answer is 503.
  • jwt.decode from 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

RequestAnswer
/api/v1/hello, no token200, hello world (still open)
/api/me, no header401, Not authenticated
Bearer abc401, Not enough segments
Valid token with one extra character401, Signature verification failed
Valid token200, 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.

One thing to tighten: this version reads the algorithm from the token's own header, 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: none and admin/admin into a real deployment.

Quick recap

FastAPIDjangoFlask
Reads the headerHTTPBearerauthenticate splits it_extract_bearer_token
Librarypython-josePyJWTPyJWT PyJWKClient
Protects a routeDepends(get_current_user)Default in settings, opt out with AllowAny@require_auth
Claims live onA parameterrequest.userg.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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 32 of 39

Previous
An Auth Starter Kit with Keycloak: Build Sign In Once, Put the Backend Between React and the Identity Provider
Next post
How an Identity Provider Login Works: The OpenID Connect Code Flow vs a Backend Password Grant, with Keycloak

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.

On this page

  • Keycloak in Docker
  • The realm file
  • The first run finds a bug
  • What's inside the token
  • The check in FastAPI
  • Test it five ways
  • The same check in Django
  • The same check in Flask
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.