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.
What you will learn
- Explain what an identity provider takes off your hands and why you shouldn't build auth yourself
- Name Keycloak's realm, client, user and session
- Walk the OpenID Connect authorization code flow with state and PKCE, and compare it with a backend password grant
- Follow one token from the login to the route that checks it, and know what refresh and logout do
Before you start
- Protecting a Python API with Keycloak
- An auth starter kit with Keycloak
The idea of an identity provider is simple: hand the whole identity job to one service, and let your app focus on its own features. Once the flow behind a login is clear, every login problem becomes much easier to read.
What an identity provider does
Keycloak gives you a login page and a sign up page out of the box, though you can use your own pages instead, which is what this kit does. It stores users and their passwords, hashed and driven by policies, so nothing is kept in plain text. It handles sessions, single sign on, and sign in with Google or other social accounts. And it's open source and self hosted, so it runs in Docker for nothing.
Why not build the login yourself? Look at the list: password hashing, sessions, password reset, email verification, one time codes, social login, refresh tokens, account lockout, rate limiting, audit logs, brute force protection and CSRF. Each one has to be built, tested and maintained, and a single mistake can expose your users. An identity provider already does all of it.
Four words you'll see everywhere
| Word | Meaning | In this kit |
|---|---|---|
| Realm | A tenant: its own users, clients and settings | subly |
| Client | An application that asks Keycloak to sign users in | subly-backend (with a client ID and secret) and subly-frontend for the hosted flow |
| User | An account in the realm | The test users |
| Session | Opened when a user signs in | Listed on the realm's sessions page |
In this kit there are three boxes. The front end talks only to the backend, and the backend is the one that talks to Keycloak. A check of the browser's requests during a login shows no call to Keycloak at all, which keeps Keycloak hidden behind one more layer.
The standard way: the authorization code flow
Before the kit's own login, here's the standard way to sign in with an identity provider. It's called the authorization code flow, and it's part of OpenID Connect.
The URL carries the client ID, response_type=code, a random state and a code_challenge. After the user signs in, Keycloak redirects back with the same state and a short code. A code isn't a token yet, so the app posts it to Keycloak's token endpoint together with the code_verifier, the secret behind the challenge. Keycloak checks them and answers with an access token, a refresh token and an ID token. And a code works only once: sent a second time, Keycloak answered "Code not valid". From here the access token rides on every API call.
This kit's way: our page, a password grant
The kit doesn't use the hosted page. It has its own login page in Next.js. You type the email and password there, the front end posts them to /auth/login on FastAPI, and FastAPI passes them to Keycloak's token endpoint with the password grant. In Keycloak that's called direct access grants, and it's switched on for the subly-backend client. Keycloak checks the password and sends the tokens back to FastAPI, which returns them to the browser. The browser made two requests: a POST to /auth/login, then a GET to /auth/me.
Both ways end with the same tokens. The difference is who sees the password. The hosted page keeps it on Keycloak's side. The custom page gives you your own look, but your page and your backend now carry the password, so in production they must run over HTTPS.
Here's the call, in auth/keycloak.py:
@staticmethod
async def login(username: str, password: str) -> dict[str, Any]:
try:
return get_openid_client().token(
username=username,
password=password,
grant_type="password",
scope="openid profile email",
)
except KeycloakAuthenticationError as exc:
raise _map_kc_error(exc, "Invalid username or password")
except KeycloakError as exc:
raise _map_kc_error(exc, "Login failed")
The OpenID client comes from python-keycloak, a library that wraps Keycloak's sign in and admin endpoints so you don't write those HTTP calls by hand. A rejected password becomes a 401, "Invalid user credentials".
How the backend finds Keycloak
keycloak_internal_url: str = "http://localhost:8080"
keycloak_issuer: str = "http://localhost:8080/realms/subly"
keycloak_realm: str = "subly"
keycloak_backend_client_id: str = "subly-backend"
keycloak_backend_client_secret: str = "<your-client-secret>"
The internal URL is where the backend reaches Keycloak. The issuer is the realm's address that every token carries. The client secret proves the backend is that client; the project ships a local sample value, and in production it comes from the environment (shown here as a placeholder). These values must match the realm, or the backend can't talk to Keycloak at all.
Follow the token
The login answer has an access token, a refresh token, expires_in 1800 (thirty minutes) and token type Bearer. The access token is a JWT. Its header says RS256 and carries a key ID that tells which of Keycloak's keys signed it. The payload has the issuer (our realm), azp saying it was issued to subly-backend, the username, the email and realm_access with the roles. It's like a passport: it carries what the API needs, and it's signed so nobody can change it unnoticed.
The front end keeps it in local storage as subly.access_token, next to the refresh token. In api.ts, every protected request adds Authorization: Bearer and the token. After the login there's no password check, only the token check. Keycloak comes back in only to refresh the token or to log out.
The check
def decode_token(token: str) -> dict[str, Any]:
try:
claims = get_openid_client().decode_token(token, validate=True)
except KeycloakError as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Invalid or expired token: {exc}",
headers={"WWW-Authenticate": "Bearer"},
) from exc
iss = claims.get("iss")
if iss != settings.keycloak_issuer:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Invalid issuer: {iss}",
headers={"WWW-Authenticate": "Bearer"},
)
return claims
HTTPBearer reads the header first, so no header at all stops at 401, not authenticated. decode_token with validate=True checks the signature against the realm's public keys (published at its certs address, picked by the key ID) and the expiry. Then our own code checks the issuer, so a token from another realm is a 401, invalid issuer. When every check passes, the claims go to the route.
Refresh, sessions and logout
- The access token is short. Before it runs out, the refresh token gets a new one from Keycloak, so the user stays signed in without typing the password again.
- Each sign in is a session in Keycloak, visible on the realm's sessions page for the
subly-backendclient. - Logout goes through Keycloak. The backend sends the refresh token, the session ends, and after that the refresh token fails with "Session not active".
- The access token is stateless. It stays valid until it expires, which is one more reason to keep its life short.
start-dev: plain HTTP and a small built-in file database. That's fine for learning. For production, Keycloak runs with start, behind HTTPS, with a proper database such as Postgres.The same flow in Django and Flask
The flow doesn't change. Only the code in the middle box does.
| Django | Flask | |
|---|---|---|
| Settings | One KEYCLOAK dictionary in settings.py, read from environment variables with local defaults | The same five settings in config.py |
| Login route | A function view with api_view and POST, made public with an empty authentication_classes and AllowAny, because the login can't ask for the token it hands out | A Login class on MethodView in an Auth blueprint under /auth |
| Body check | A LoginRequest serializer; a bad body is a 400 with a message per field | A marshmallow schema; a missing password is a 422, "Missing data for required field" |
| Token check | KeycloakAuthentication.authenticate calls decode_token, then checks the issuer; failures become 401 through AuthenticationFailed | require_auth calls decode on a shared KeycloakService, puts the claims on g.user; every decode error becomes a 401 |
| No header | 401, no credentials were sent | 401, Missing Bearer token |
In Flask, a small helper kc_call turns Keycloak errors into a Flask abort, so a wrong password is still a 401, with message in the JSON where FastAPI sent detail. In Django the Swagger page comes from drf-spectacular at /docs, with the same auth routes.
Common mistakes
- Thinking the code from the redirect is a token. It has to be traded at the token endpoint, once.
- Running a custom login page over plain HTTP outside your own machine. The password travels through your page and backend.
- Expecting logout to kill an access token someone already copied.
Quick recap
- Keycloak is an open source identity server, so you don't write auth from scratch.
- The front end talks to the backend, and the backend talks to Keycloak.
- After login every request carries a token: a signed passport that expires quickly.
- FastAPI checks the signature, the expiry and the issuer before any route code runs.
- Logout goes through Keycloak, and production runs on HTTPS.
Try it yourself
Open the backend's Swagger page, log in, and call /auth/me once with the token (paste it with Authorize) and once without it. Compare the answers.
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.
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.
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.
