Keycloak Middleware Issue: Empty preferred_username in get_user Object I'm using fastapi_keycloak_middleware to secure my FastAPI app with Keycloak. I'm having trouble mapping the preferred_username claim from the JWT token to the FastApiUser object.
Despite explicitly setting preferred_username_claim="preferred_username" in the configuration, the user.preferred_username attribute is always empty inside my secure endpoint. The claim definitely exists in the Keycloak token, and other claims like sub (mapped to user_id) work fine.
How can I correctly map the preferred_username so it's accessible via user.preferred_username?
from fastapi import FastAPI
from fastapi_keycloak_middleware import KeycloakConfiguration, KeycloakMiddleware
from fastapi_keycloak_middleware import get_user
from fastapi import Depends
import logging
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("fastapi_keycloak_middleware").setLevel(logging.DEBUG)
logging.getLogger("fastapi").setLevel(logging.DEBUG)
# 1. Keycloak Client Configuration
keycloak_config = KeycloakConfiguration(
url="http://keycloak:8080/",
realm="demo-realm",
client_id="fastapi-client",
client_secret="vSZr8BcWWO8TiN1IMxC12fYLgmAuZvlm" ,
authentication_scheme="Bearer" ,
# These claims MUST be present in the token (Check)
claims=["sub", "name", "email", "preferred_username", "given_name", "family_name"],
reject_on_missing_claim=True,
# 🔑 IMPORTANT: Explicit Mapping (The source of the issue?)
preferred_username_claim="preferred_username", # Mapped claim
user_id_claim="sub", # This maps correctly
first_name_claim="given_name",
last_name_claim="family_name",
)
app = FastAPI()
# 2. Add Keycloak Middleware
app.add_middleware(
KeycloakMiddleware,
keycloak_configuration=keycloak_config
)
# Secure Endpoint
@app.get("/secure")
def secure(user = Depends(get_user) ):
print("-----------------------------------------------------------------")
print("CONTENT OF THE 'user' OBJECT (FastApiUser):")
try:
# user.preferred_username is always empty/defaulted
user_id = getattr(user, 'user_id', 'Unknown ID')
username = getattr(user, 'preferred_username', 'Unknown User')
except Exception as e:
print(f"ERROR READING THE USER OBJECT: {e}")
username = "ERROR"
print("-----------------------------------------------------------------")
return {"message": f"Hello {username} ({user_id}), this endpoint is secured!"}