3.2.4
This guide shows you how to secure your FastMCP server using Keycloak OAuth. This integration uses the Remote OAuth pattern with Dynamic Client Registration (DCR), where Keycloak handles user login and your FastMCP server validates the tokens.
Keycloak 26.6.0 or later is required. Earlier versions had a DCR incompatibility with MCP clients (PR #45309) that is fixed in 26.6.0.
Configuration
Prerequisites
Before you begin, you will need:- A running Keycloak instance (e.g.,
http://localhost:8080) - A Keycloak realm with Dynamic Client Registration enabled and a trusted host policy that allows your server URL (e.g.,
http://localhost:8000/*) - Your FastMCP server’s public URL (e.g.,
http://localhost:8000)
FastMCP Configuration
Create your FastMCP server and useKeycloakAuthProvider to handle OAuth:
server.py
required_scopes defaults to ["openid"], which ensures the sub claim is present in access tokens. Pass your own list to require additional scopes.
Local Development
Local infrastructure tooling is deliberately kept out of the FastMCP core library to keep auth integrations slim and the associated maintenance burden as low as possible. That said, Keycloak is a popular identity provider for local development and testing, so a dedicated FastMCP-compatible setup blueprint lives in the companion project fastmcp-keycloak-local. It provides everything needed to develop and test FastMCP servers with Keycloak OAuth locally: a Docker-based Keycloak setup with a pre-configuredfastmcp realm (Dynamic Client Registration enabled, test user included), cross-platform start scripts, and integration guides for the MCP Inspector, Claude Desktop, and Claude Code CLI.
Testing
Running the Server
Testing with a Client
client.py
Features
JWT Token Validation
- Signature Verification: Validates tokens against Keycloak’s JWKS endpoint
- Expiration Checking: Automatically rejects expired tokens
- Issuer Validation: Ensures tokens come from your specific Keycloak realm
- Scope Enforcement: Verifies required OAuth scopes are present
- Audience Validation: Optional validation that tokens target your server (configure
audience)
User Claims
Access user information from Keycloak JWT tokens:Advanced Configuration
Custom Token Verifier
Passtoken_verifier to replace the default JWTVerifier. The provider’s required_scopes and audience only configure the default verifier, so set them on your custom verifier instead.