Fastapi Keycloak Middleware
You set up a fastapi keycloak middleware by checking user tokens on every request. The app reads the token, checks the key, and lets valid users log in. Engineering teams use this flow to centralize identity across many web apps. Yet broad roles often give one logged-in user full read and write power. When an account has wide permissions, one bad request can change or leak data. How a fastapi keycloak middleware works in practice A request starts when a user or service logs in through Keycloa
Your coding agents run with your access.
Claude Code reaches prod with a developer's credentials, and approval prompts get clicked through. hoop.dev checks every query, masks sensitive data, and holds risky changes for a human.
You set up a fastapi keycloak middleware by checking user tokens on every request. The app reads the token, checks the key, and lets valid users log in. Engineering teams use this flow to centralize identity across many web apps. Yet broad roles often give one logged-in user full read and write power. When an account has wide permissions, one bad request can change or leak data.
How a fastapi keycloak middleware works in practice
A request starts when a user or service logs in through Keycloak. Keycloak checks the user credentials and sends back a signed JSON Web Token. The client app includes this token in the header of every web call. Your FastAPI app catches each call before the main route code runs. You can run this check across all routes or on single routes.
The app fetches public keys from the Keycloak realm to check the token signature. It also checks the token end time and the target audience claim. Next, the code pulls realm roles and client roles from the token payload. The route handler checks if the user role matches the rule for that path. If the role matches, the app runs the route logic and sends data back. If the check fails, the app stops the call and returns an error code.
Managing roles and token checks across services
As your team builds more services, role checks get hard to track. You must keep role names in sync between Keycloak realms and Python code. A small change in a realm role can break access across several services. Developers often create wide admin roles just to keep apps running during updates. Those wide roles stay in place long after the test phase ends.
Caching public keys is also vital for good app speed under heavy load. If the app fetches keys on every call, network lag will slow down responses. If the app caches keys too long, a key change will block valid users. Teams must also handle token refresh flows and short token life spans. Even when you fix these issues, token checks only guard the front door.
Keycloak + AI Proxy & Middleware Security: architecture patterns and best practices
Continue reading? Get the full guide.
Free. No spam. Unsubscribe anytime.
What native token checks solve and what they miss
This native setup solves user login and basic role checks very well. You do not need to store user passwords inside your FastAPI database. Your team can turn off a user account in one central place. You can also group users by team and assign base roles with ease.
Still, token checks only decide who can start a request to an endpoint. Once the user passes the role check, the app trusts the request body. The app service account then runs queries against your database with full power. Native token checks do not inspect what individual queries or commands do in flight. They do not rewrite sensitive fields like emails, phone numbers, or card numbers. A user with a valid token can pull thousands of raw customer records. You also lack a detailed log that ties each database action to one person.
Check HTTP API requests and responses on the wire
API gateways and auth headers decide who may call an internal service. Request checks alone cannot read the response body where sensitive data leaves the service. With hoop.dev, you run an open-source proxy, a sidecar for your HTTP API. It runs beside an internal HTTP service or behind Envoy while keeping the API's own auth in place.
Dynamic path segments like IDs and UUIDs collapse to wildcards so one rule in hoop.dev guardrails can refuse banned methods or paths before execution with a 403 error. On the way back, hoop.dev data masking walks JSON payloads by key path and rewrites matched sensitive values in memory. Every request and decision is logged per caller, and hoop.dev is MIT licensed on GitHub.
Frequently asked questions
Should I use request middleware or route dependencies in FastAPI?
Route dependencies work best when different endpoints need specific role checks. App middleware works well when you want to check tokens on every single path. Many teams combine both methods to handle global checks and specific route rules.
How does the app check tokens without calling Keycloak every time?
The app downloads the public signing keys from Keycloak and saves them in memory. It uses these saved keys to check the token signature right inside the app. This local check is fast and avoids extra network calls on each request.
Why do valid tokens still leave backend databases at risk?
A valid token only proves who the user is at the web layer. After that check, the app uses one shared database account to run queries. Without query checks or field masking, any valid route call can pull raw data.
Related guides
In this post