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

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Authentication

What you will learn

  • List the four pillars every auth starter kit needs
  • Swap the backend framework with one BACKEND variable and keep the front end
  • Write a fix prompt that makes a coding agent test its own work
  • Run register, login, me and logout through the backend so the browser never calls Keycloak

Before you start

  • Docker Compose basics
  • What a JWT is

Think about the projects you'll build. Almost every one needs users to sign in. So there's a sign in button, a callback page, an error page and a sign out. On the backend, every protected route has to check a token, and the settings for all of this have to sit somewhere. Writing these again for each project is the same work every time. So build them once, in a starter kit, and reuse it.

Starting from scratch is like moving into an empty house with no kitchen and no plumbing. A starter kit is a house where the kitchen and the beds are already in. You still decorate it your own way, but you don't start by fitting the plumbing.

Four pillars

  1. Sign in and sign out on the front end.
  2. Sample pages: the signed in page, the callback page and the error page.
  3. User authentication on the backend, with one protected route, /me.
  4. Configuration, with every setting in one .env file.

That's all a kit does. No feature work yet, only the things every project repeats.

One switch picks the backend

The Keycloak kit has a React front end, three backends (FastAPI, Flask and Django), a keycloak folder with a ready realm (the client, a test user and two roles), and a Compose file. The backend's build line is backend- followed by the BACKEND variable, with fastapi as the default. Set it to flask or django and only the backend changes. Here's the kit's .env.example as a template (the kit's own README calls these placeholders); it holds addresses and names, no secrets:

# ---- Backend selection ----
BACKEND=fastapi                  # fastapi | flask | django

# ---- Keycloak (server-side) ----
KC_REALM_URL=http://keycloak:8080/realms/starter
KC_JWKS_URL=http://keycloak:8080/realms/starter/protocol/openid-connect/certs
KC_CLIENT_ID=starter-web
KC_AUDIENCE=account              # what backend expects in JWT 'aud'
KC_ISSUER=http://localhost:8080/realms/starter

# ---- Frontend (Vite reads VITE_*) ----
VITE_KC_REALM_URL=http://localhost:8080/realms/starter
VITE_KC_CLIENT_ID=starter-web
VITE_KC_REDIRECT_URI=http://localhost:5173/callback
VITE_API_BASE_URL=http://localhost:8000

Each backend protects /me its own way. FastAPI asks for get_current_user with Depends. Flask puts a decorator on the route and reads the user from g. Django uses a REST framework authentication class. Called with the test user's token, all three returned the same sub, the same email and the role user, and without a token each answered 401. The token check itself is in protecting a Python API with Keycloak.

The Cognito kit has the same shape: same front end, same three backends, same /me. There's no keycloak folder and Compose has only the backend and front end, because Cognito runs at AWS. You give it the region, the user pool ID and the app client ID, and the issuer and keys address are built from them. Keycloak is self hosted in Docker and costs nothing; Cognito is managed and scales without you running anything. AWS has a free tier, but some usage can still be charged, so keep an eye on billing.

Finishing the kit: a fix prompt

From here on the example is the subtitle app built on the kit, so the names change: the realm is subly and the Next.js front end runs on port 3000, where the generic kit used starter and Vite on 5173. After Keycloak was first added, four things were wrong. The backend didn't start. The front end used the login pages Keycloak hosts, and we want our own React pages for login, sign up, logout and profile. The front end talked to Keycloak directly, and we want the browser to talk only to our backend. And Keycloak printed startup warnings. When you ask an AI tool to fix something, a clear list of what's wrong is the first thing to give it. Here's the prompt, trimmed:

Re-audit and fix the existing Docker + backend + frontend + Keycloak setup.

Issues:
- Backend does not start.
- Frontend currently uses Keycloak-hosted auth pages.
- I need custom React login, signup, logout, and profile pages.
- Frontend must never talk directly to Keycloak.
- Backend must sit between React and Keycloak.
- Keycloak startup warnings should be fixed where possible.

Required flow:

React custom auth UI → Backend auth APIs → Keycloak

Tasks:
...
5. Add/verify backend APIs:

   POST /auth/register
   POST /auth/login
   POST /auth/logout
   GET /auth/me
   GET /health
...
Verification:
- Do not rebuild the whole app from scratch.
- Keep the existing implementation and fix it cleanly.
- Run:

   docker compose up --build

- Test backend, frontend, Keycloak, register, login, /auth/me, logout, and protected routes.
- Come back only when everything is running and ready to test.
- Summarize exactly which files changed and why.
- Mention any remaining warnings or limitations.

It starts with "re-audit", so the agent checks everything, not only the file you suspect. It says what's wrong, then exactly what to do, then how to check its own work. If you find yourself prompting again and again for the same fix, your prompt probably needs rules like these. For that the agent needs permission to run terminal commands. On a small kit, letting it run on its own is fine. On a production app, don't bypass permissions: understand each change and review every edit.

The shape of the fixed kit

Backend between React and Keycloak React pages port 3000 FastAPI port 8000 Keycloak port 8080, in Docker /auth/login, /auth/me tokens, users never: browser to Keycloak
The page talks only to the backend. The backend talks to Keycloak inside Docker. Checked in the browser: login, auth me and logout all went to the backend, none to Keycloak.

In the fixed docker-compose.yml, the healthcheck that kept failing now uses Keycloak 26's own health endpoint. With KC_HEALTH_ENABLED set to true, Keycloak serves /health/ready on port 9000, and the probe uses plain bash so it doesn't need curl in the image:

    healthcheck:
      test: ["CMD-SHELL", "exec 3<>/dev/tcp/127.0.0.1/9000 && printf 'GET /health/ready HTTP/1.0\\r\\n\\r\\n' >&3 && head -n 1 <&3 | grep -q '200'"]
      interval: 10s
      timeout: 5s
      retries: 30
      start_period: 30s

The backend waits for a healthy Keycloak and reaches it by its service name. The front end is built with one address, NEXT_PUBLIC_API_URL: http://localhost:8000, the backend's. One docker compose up --build brings all three up. Keycloak still warns that it's in development mode, which is expected on your own machine.

The five routes

The routes sit in auth_controller.py under /auth, and the module comment says it plainly: the frontend calls these, never Keycloak directly.

Register

@router.post(
    "/register",
    response_model=RegisterResponse,
    status_code=status.HTTP_201_CREATED,
    summary="Register a new user via Keycloak",
)
async def register(body: RegisterRequest) -> RegisterResponse:
    await keycloak_client.register(
        email=body.email,
        password=body.password,
        first_name=body.first_name,
        last_name=body.last_name,
    )
    return RegisterResponse(message="User registered")

Behind it, the Keycloak admin client from python-keycloak calls create_user, with the email as the username and a password that isn't temporary. The first time you get 201, user registered. Send the same email again and Keycloak refuses it, so you get 409, "User exists with same email". After a successful sign up the page logs the new user in straight away.

Login and me

Login takes an email and password and asks Keycloak for tokens with the password grant. Keycloak sends back an access token and a refresh token, and expires_in is 1800, so the access token is good for thirty minutes. A wrong password becomes a 401 with "Invalid user credentials", the exact text the login page shows in red. /auth/me depends on get_current_user, so without a token it's 401, not authenticated; with one it returns the user ID, email, name and roles from realm_access. The seeded test user has an empty roles list; a user registered through the backend gets three default roles from the realm. No route is blocked by role yet, but a role check is now just a comparison against that list. How the login and the token check work is in the identity provider flow with Keycloak.

Logout

async def logout(body: LogoutRequest | None = None) -> LogoutResponse:
    if body is None or not body.refresh_token:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="refresh_token is required",
        )
    await keycloak_client.logout(body.refresh_token)
    return LogoutResponse(ok=True)

At login the page saves both tokens in the browser, as subly.access_token and subly.refresh_token. On logout it sends the refresh token to this route, the backend passes it to Keycloak, and Keycloak ends that session. Then the page clears both tokens and the protected pages send you back to login.

One limitation worth knowing: the backend checks the access token on its own, so an old access token still passes /auth/me until its thirty minutes are up. That's fine for a starter kit, because the page has already thrown that token away. Keep the access token's life short.

The kit, end to end

  • Open the dashboard without logging in: you land on the login page.
  • Wrong password: "Invalid user credentials".
  • The test user: the dashboard opens, and Call auth me returns the user with an empty roles list.
  • Log out: back to the login page.

There's no subtitle feature yet, and that's the point. It's a working login, ready for features.

Common mistakes

  • Letting the front end import a Keycloak library "just for login". Then the browser knows the identity provider, and the backend is no longer the only door.
  • Forgetting that logout needs the refresh token. Without it the route answers 400.
  • Treating logout as instant everywhere. A copied access token works until it expires.

Quick recap

  • A starter kit is sign in, sign out, the token check and the settings, built once and reused.
  • One BACKEND variable swaps FastAPI, Flask or Django behind the same front end.
  • A good fix prompt says what's wrong, what to do, and how the agent checks its own work.
  • The page talks only to the backend; the backend talks to Keycloak for register, login and logout.

Try it yourself

Log in, call auth me, log out, and then open the dashboard again to see where it takes you.

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 · 31 of 39

Previous
How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
Next post
Protecting a Python API with Keycloak: Check the JWT Signature, Issuer and Expiry in FastAPI, Django and Flask

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.

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.

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

  • Four pillars
  • One switch picks the backend
  • Finishing the kit: a fix prompt
  • The shape of the fixed kit
  • The five routes
  • Register
  • Login and me
  • Logout
  • The kit, end to end
  • 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.