Skip to main content

fastapi-keycloak-admin

PyPI Python CI License: MIT

Authentication, account and user management for FastAPI applications that use Keycloak as their identity provider. It validates Keycloak access tokens, lets your frontend keep its own login form, lets users manage their own account, and lets administrators create users with any realm roles. Neither the browser nor your code ever has to talk to Keycloak directly.

The project is currently alpha software. Pin the version, test upgrades in a staging environment, and review the security notes before using it in production.

It is the FastAPI counterpart of litestar-keycloak-admin: the same endpoints, the same error format, the same login verification by code.

Concern Provided as
Validating access tokens (JWKS, exp, iss, aud, typ) CurrentUser dependency
Role and scope checks require_roles, require_client_roles, require_scopes, requires_admin
Login with username and password, refresh, logout built-in endpoints
Replacing a temporary password at first login built-in endpoints
Own profile and password, optional login code by e-mail built-in endpoints
Listing realm roles, registering users built-in endpoints (admin only)
Creating users from the command line (e.g. the first admin) fastapi-keycloak-admin create-user

Contents: Installation · Quick start · Keycloak setup · Protecting routes · Login flow · Endpoints · Errors · Configuration · Command line · Using the client · Public API · Security notes

Installation

Python 3.12 or newer and FastAPI 0.115 or newer are required.

# pip
python -m pip install fastapi-keycloak-admin

# or uv
uv add fastapi-keycloak-admin

It depends on aiohttp, PyJWT (with cryptography) and click; they are installed with it.

Quick start

from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi_keycloak_admin import (
    KeycloakAdmin,
    KeycloakAdminConfig,
    KeycloakUser,
    MatchStrategy,
    require_roles,
)

app = FastAPI()
KeycloakAdmin(KeycloakAdminConfig.from_env()).init_app(app)

analysts = require_roles("admin", "analyst", strategy=MatchStrategy.ANY)


@app.get("/reports")
async def reports(user: Annotated[KeycloakUser, Depends(analysts)]) -> dict[str, str]:
    return {"requested_by": user.preferred_username or user.sub}

With KEYCLOAK_INTERNAL_URL, KEYCLOAK_REALM, KEYCLOAK_CLIENT_ID and KEYCLOAK_CLIENT_SECRET set, the application now has:

  • /reports open to users holding admin or analyst;
  • the auth endpoints under /auth (see Endpoints);
  • an Authorize button in /docs that takes an access token.

A minimal local environment looks like this:

KEYCLOAK_INTERNAL_URL=http://localhost:8080
KEYCLOAK_REALM=my-realm
KEYCLOAK_CLIENT_ID=my-backend
KEYCLOAK_CLIENT_SECRET=replace-me

# Optional: use a master-realm administrator for local development.
KEYCLOAK_ADMIN=admin
KEYCLOAK_ADMIN_PASSWORD=replace-me-too

Keep secrets outside source control. In production, prefer a narrowly scoped service account as described below.

Keycloak setup

The package expects:

  1. A confidential client (Client authentication On) with Direct access grants enabled. This is the client the backend uses for the password grant. Its ID and secret go into KEYCLOAK_CLIENT_ID / KEYCLOAK_CLIENT_SECRET.
  2. An audience mapper on that client, so access tokens carry its ID in aud (Client scopes → dedicated scope → Add mapper → Audience). Tokens whose azp is the client are accepted without it, unless strict_audience is set.
  3. Realm roles for your application, e.g. admin, user, dispatcher. They are not listed anywhere in code: define them in Keycloak (or in the realm export you import) and they can be assigned and checked right away. One realm role, admin by default, is the admin role: its holders may list roles and register users.
  4. Admin REST API access, in one of two ways:
    • set KEYCLOAK_ADMIN / KEYCLOAK_ADMIN_PASSWORD to a master-realm administrator (simplest, fine for development); or
    • leave them unset and enable Service accounts on the client, then give its service account the realm-management roles manage-users and view-realm (recommended in production: the backend gets only the rights it needs, in one realm).

A minimal realm export with both roles and the client:

{
  "realm": "my-realm",
  "roles": {
    "realm": [
      { "name": "admin", "description": "Full administrative access" },
      { "name": "user", "description": "Regular user" }
    ]
  },
  "clients": [
    {
      "clientId": "my-backend",
      "publicClient": false,
      "secret": "${KEYCLOAK_CLIENT_SECRET}",
      "directAccessGrantsEnabled": true,
      "standardFlowEnabled": false,
      "protocolMappers": [
        {
          "name": "audience",
          "protocol": "openid-connect",
          "protocolMapper": "oidc-audience-mapper",
          "config": { "included.client.audience": "my-backend", "access.token.claim": "true" }
        }
      ]
    }
  ]
}

Protecting routes

Routes are public unless they depend on the caller. There is no middleware: authentication is a FastAPI dependency, so it shows in the OpenAPI schema and applies exactly where it is declared.

Take the caller as a parameter with CurrentUser:

from fastapi_keycloak_admin import CurrentUser


@app.get("/profile")
async def profile(user: CurrentUser) -> dict[str, str]:
    return {"id": user.sub, "email": user.email or ""}

It is a KeycloakUser with sub, preferred_username, email, given_name, family_name, realm_roles, client_roles, scopes and every raw claim in claims. Without a valid token the request fails with 401 before the route runs.

Restrict a route to certain roles with one of the checks. Each is a dependency that returns the caller, so it can be a parameter or sit in dependencies=[...] of a route or a whole router:

from fastapi import APIRouter, Depends
from fastapi_keycloak_admin import (
    MatchStrategy,
    require_client_roles,
    require_roles,
    requires_admin,
)

require_roles("admin", "dispatcher", strategy=MatchStrategy.ANY)  # holds at least one of them
require_roles("dispatcher", "supervisor")  # holds every one of them
require_client_roles("billing", "read")  # a role of the client "billing"
requires_admin  # holds the configured admin role

staff = APIRouter(dependencies=[Depends(require_roles("staff"))])

Note: require_roles defaults to MatchStrategy.ALL. For "any of these roles", which is what most role checks mean, pass strategy=MatchStrategy.ANY explicitly.

A caller lacking the roles gets 403. FastAPI caches dependencies per request, so the token is validated once however many checks a route has.

Login flow

The endpoints are designed for a browser frontend with its own login form:

  1. Log in: POST /auth/login with {"username", "password"}. The response holds the access token. The refresh token is set as an httponly cookie and is never visible to JavaScript.
  2. First login of a new user: users created by an admin have a temporary password, so the login responds 403 with the reason passwordChangeRequired (see Errors). The frontend asks for a new password and calls POST /auth/initial-password with {"username", "password", "new_password"}. On success it returns tokens, just like a login.
  3. Calling the API: send Authorization: Bearer <token>.
  4. Keeping the session alive: before the access token expires (expires_in, in seconds), call POST /auth/refresh, or call it when an API request fails with the reason expired. The browser sends the cookie on its own; no body is needed. A 401 from /refresh itself means the Keycloak session is over and the user has to log in again.
  5. Logging out: POST /auth/logout ends the Keycloak session and clears the cookie. Dropping the access token in the browser alone would leave the session usable until it expires.

For non-browser clients (mobile apps, scripts), disable the cookie with refresh_cookie=RefreshCookieConfig(enabled=False): the refresh token is then returned in the response body and sent back as {"refresh_token": "..."} to /refresh and /logout.

Login verification by code

Set login_verification to require a one-time code after the password. The application decides how the code reaches the user - the package only calls send_code:

from fastapi_keycloak_admin import KeycloakAdminConfig, LoginCode, LoginVerificationConfig


async def send_code(code: LoginCode) -> None:
    await mailer.send(code.email, f"Your login code: {code.code}")  # or publish to a queue


config = KeycloakAdminConfig.from_env(
    login_verification=LoginVerificationConfig(send_code=send_code),
)

POST /login and POST /initial-password then check the password and answer 202 {"challenge_id", "expires_in", "destination": "a***@example.com", "code_required": true} instead of tokens. POST /login/verify with the right code returns the usual TokenResponse (and the refresh cookie); POST /login/resend sends a new code for the same challenge.

  • The Keycloak tokens of the checked password wait in LoginVerificationConfig.store and are refreshed on success. The default MemoryChallengeStore lives in one process; when the app runs several workers, pass a shared store:

    from redis.asyncio import Redis
    from fastapi_keycloak_admin import LoginVerificationConfig, RedisChallengeStore
    
    LoginVerificationConfig(send_code=send_code, store=RedisChallengeStore(Redis.from_url(url)))
    

    Any object with async get, set(key, value, expires_in) and delete (ChallengeStore) works as well.

  • The code is kept only as an HMAC; max_attempts wrong codes (default 5) end the Keycloak session. Codes live ttl_seconds (300); resend_interval_seconds (60) and max_sends (4) limit resending.

  • The e-mail comes from the access token's email claim; an account without one gets 403 emailRequired. A send_code that raises gives 503 codeDeliveryFailed.

  • Error reasons: invalidCode (401), challengeExpired (401), tooManyAttempts (429), tooManySends (429), resendTooSoon (429 with Retry-After).

Letting users turn the code off

With LoginVerificationConfig(user_choice=True) every user decides for themselves:

Method and path Body Success
GET /me/login-verification 200, {"enabled": bool, "changeable": bool}
PUT /me/login-verification enabled, password (the current one) 200, same body

The choice lives in the user attribute user_attribute (default login_verification, off skips the code), written through the Admin API with the other attributes kept - the realm must allow it (User Profile unmanagedAttributePolicy ADMIN_EDIT or a declared attribute). The code stays required for everyone who has not turned it off and whenever the attribute cannot be read. Without user_choice the PUT answers 404.

Endpoints

All paths are relative to auth_path (default /auth).

Public (no token)

Method and path Body Success
POST /login username, password 200, TokenResponse
POST /initial-password username, password (the temporary one), new_password 200, TokenResponse
POST /refresh refresh_token (only without the cookie) 200, TokenResponse
POST /logout refresh_token (only without the cookie) 204
POST /login/verify challenge_id, code 200, TokenResponse
POST /login/resend challenge_id 202, LoginChallengeResponse

The last two exist only with login_verification; otherwise they answer 404.

TokenResponse is {"token": str, "expires_in": int, "refresh_expires_in": int, "refresh_token": str | null}; refresh_token is null while the cookie is enabled.

Any authenticated user

Method and path Body Success
GET /me 200, UserResponse
PATCH /me any of first_name, last_name, email ("" removes the e-mail) 200, UserResponse
POST /password current_password, new_password 204

UserResponse is {"id", "username", "email", "first_name", "last_name", "roles": [str]}. It is built from the access token, so after PATCH /me the token itself keeps the old values until it is refreshed.

Admin role only

Method and path Body Success
GET /roles 200, [{"name", "description"}]
POST /register username, password, roles: [str], optional email, first_name, last_name 201, UserResponse

GET /roles returns the realm's own roles and leaves out Keycloak's built-in ones (offline_access, uma_authorization, default-roles-<realm>). Use it to fill a role picker.

POST /register creates the user with a temporary password and the given roles, at least one. It fails with 400, and creates nothing, if a role doesn't exist in the realm or isn't in assignable_roles.

To mount the endpoints yourself (another prefix, extra dependencies), call init_app(app, include_router=False) and include fastapi_keycloak_admin.routes.router; set refresh_cookie.path to the new prefix so the browser sends the cookie back.

Errors

Errors of the built-in endpoints, of tokens and of the role checks have the same shape:

{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "invalidParameter",
        "message": "Password must be at least 8 characters long",
        "locationType": "body",
        "location": "password"
      }
    ],
    "code": 400,
    "message": "Password must be at least 8 characters long"
  }
}
  • code repeats the HTTP status, and message is meant for humans.
  • errors[].reason is the stable, machine-readable part: branch on it, not on the message.
  • location and locationType say what the error is about, when that is known: a body field (body), a query or path parameter (query, path), or a header (header, e.g. Authorization).
Status reason When
400 invalidParameter A field is missing, has the wrong type or fails a check (password too short, no roles); one item per field
400 invalid Keycloak refused the input: role missing from the realm, password breaks the realm's policy
400 badRequest Malformed request, e.g. invalid JSON
401 required No access token, or no session to refresh
401 expired The access token has expired: refresh it
401 authError Invalid token, wrong credentials, expired or ended session
403 passwordChangeRequired Login with a temporary password: call /initial-password
403 insufficientPermissions The caller lacks a required role
403 insufficientScope The token lacks a required scope
409 conflict User or e-mail already exists; /initial-password for an account without a temporary password
500 internalError Unexpected server error; no details are exposed
502 backendError Keycloak answered with something unexpected
503 backendError Keycloak is unreachable

Token errors also set WWW-Authenticate: Bearer. Validation errors use 400, not FastAPI's usual 422, on the built-in endpoints.

init_app registers handlers for KeycloakClientError, KeycloakTokenError and ApiError, unless the app already has its own for them. The rest of the application keeps FastAPI's format ({"detail": ...}, 422). To use this format everywhere, including FastAPI's own 404, 405 and validation errors and unhandled exceptions:

from fastapi_keycloak_admin import install_error_handlers

install_error_handlers(app)

Or only for some routers: APIRouter(route_class=KeycloakRoute). In your own routes, raise ApiError(status, message, [ErrorItem(reason=..., message=...)]) answers in this format from anywhere, and error_response(...) builds a response directly.

Configuration

KeycloakAdminConfig.from_env() reads these variables (prefix KEYCLOAK_, change it with from_env(prefix=...)):

Variable Required Meaning
INTERNAL_URL yes Where the backend reaches Keycloak, e.g. http://keycloak:8080
REALM yes Realm name
CLIENT_ID yes The confidential client (see Keycloak setup)
CLIENT_SECRET yes Its secret
ISSUER no Expected iss: the URL users reach Keycloak at, plus /realms/<realm>. Needed when it differs from INTERNAL_URL, e.g. behind a reverse proxy
AUDIENCE no Expected aud; defaults to CLIENT_ID
ADMIN, ADMIN_PASSWORD no Master-realm administrator for the Admin REST API; without them the client's service account is used
REFRESH_COOKIE_PATH no Cookie path when a reverse proxy serves the API under a prefix, e.g. /api/auth; otherwise the browser never sends the cookie back

Keyword arguments refine the result:

  • keycloak={...} passes extra arguments to KeycloakConfig:

    Field Default Meaning
    optional_audiences frozenset() More audiences to accept, e.g. other clients calling the API
    strict_audience False Only aud counts; by default a token whose azp is accepted passes too
    expected_token_type "Bearer" Required typ; rejects ID and refresh tokens. None skips the check
    algorithms ("RS256",) Accepted signing algorithms
    jwks_cache_ttl 3600 Seconds the signing keys are cached
  • other arguments override KeycloakAdminConfig fields:

    Field Default Meaning
    admin_role "admin" Realm role allowed to list roles and register users
    assignable_roles () Roles registration may assign; empty means every realm role
    auth_path "/auth" Where the endpoints are mounted
    refresh_cookie RefreshCookieConfig() enabled, name (kc_refresh), path, secure, samesite (strict)
    min_password_length 8 Checked before Keycloak's own password policy
    timeout 10 Seconds per request to Keycloak
    login_verification None See Login verification by code

KeycloakAdminConfig(keycloak=KeycloakConfig(...), ...) can also be built directly, without environment variables.

Command line

The package installs a fastapi-keycloak-admin command. Its main use is creating the first administrator, when nobody can log in to /register yet. It reads the same KEYCLOAK_* variables as from_env:

KEYCLOAK_NEW_USER_PASSWORD='temporary-secret' \
  fastapi-keycloak-admin create-user root --role admin --exist-ok
  • --role may be repeated to assign several roles;
  • the password comes from KEYCLOAK_NEW_USER_PASSWORD or an interactive prompt, never from command-line arguments, which other processes can see;
  • the password is temporary: the user replaces it at first login;
  • --exist-ok exits successfully if the user already exists, so the command is safe to run on every deployment;
  • fastapi-keycloak-admin --env-prefix MYAPP_KC_ create-user ... reads other variables.

Using the client in your own code

KeycloakAdminClient is available to any route as the KeycloakAdminDep dependency, for user-management needs beyond the built-in endpoints. For example, an administrator resetting a user's password to a temporary one, which the user replaces at the next login:

from fastapi import Depends
from pydantic import BaseModel
from fastapi_keycloak_admin import ApiError, KeycloakAdminDep, requires_admin


class ResetPasswordRequest(BaseModel):
    password: str


@app.post(
    "/users/{username}/reset-password",
    status_code=204,
    dependencies=[Depends(requires_admin)],
)
async def reset_password(
    username: str, data: ResetPasswordRequest, keycloak_admin: KeycloakAdminDep
) -> None:
    subject = await keycloak_admin.find_user_id(username)
    if subject is None:
        raise ApiError(404, f"User {username!r} not found")
    await keycloak_admin.set_password(subject, data.password, temporary=True)
Method Does
login(username, password) Password grant; returns Keycloak's token response
refresh(refresh_token) New tokens for a live session
logout(refresh_token) Ends the session
check_password(username, password) Whether the password is the user's current one
complete_initial_password(username, password, new_password) Replaces a temporary password and logs in
list_roles() The realm's own roles, without Keycloak's built-in ones
create_user(username=..., password=..., roles=..., ...) Creates a user, returns its subject id
update_user(subject, **representation) Partial update with Keycloak's UserRepresentation field names
set_password(subject, password, temporary=False) Sets a password
get_user(subject) The full UserRepresentation, or None
set_user_attribute(subject, name, values) Replaces one user attribute, keeps the others
find_user_id(username) Subject id for an exact username, or None

Its errors (KeycloakClientError and subclasses) are turned into the HTTP responses listed in Errors wherever they are raised.

Public API

Everything below is importable from fastapi_keycloak_admin; other modules are internal, except fastapi_keycloak_admin.routes.router.

Name Kind
KeycloakAdmin Installs everything on the application with init_app(app)
KeycloakAdminConfig, KeycloakConfig, RefreshCookieConfig Configuration
CurrentUser, KeycloakUser, get_current_user The authenticated caller
require_roles, require_client_roles, require_scopes, requires_admin, MatchStrategy Access checks
KeycloakAdminClient, KeycloakAdminDep, get_keycloak_admin Asynchronous client for Keycloak's token endpoints and Admin REST API
LoginVerificationConfig, LoginCode, LoginCodeSender Login verification by code
ChallengeStore, MemoryChallengeStore, RedisChallengeStore Where pending challenges wait
UserResponse, LoginChallengeResponse, LoginVerificationSettings Response models of the built-in endpoints
ApiError, ErrorItem, error_response, install_error_handlers, KeycloakRoute The error format
KeycloakClientError, KeycloakUnavailableError, KeycloakLoginError, PasswordChangeRequiredError, KeycloakAdminError, LoginChallengeError Client exceptions
KeycloakTokenError, AuthenticationError, MissingTokenError, TokenExpiredError, InvalidTokenError, AuthorizationError, InsufficientRoleError, InsufficientScopeError, JWKSFetchError Token and access exceptions

The package follows Semantic Versioning; while it is in 0.x, a minor release may contain breaking changes, which are listed in the changelog.

Security notes

  • Password grant. The login endpoints use OAuth's Resource Owner Password Credentials grant: the password passes through your backend to Keycloak and is never stored. It is what allows a custom login form, but OAuth 2.1 deprecates it, and it rules out Keycloak features that need its own login page (social login, WebAuthn, its two-factor flows). If you need them, use the Authorization Code flow in the frontend; CurrentUser and the role checks work with those tokens just the same.
  • Token validation. Tokens are checked locally against the realm's JWKS: signature, exp, typ, iss and aud/azp. A revoked session's access token stays valid until it expires, so keep Keycloak's access token lifespan short. Signing keys are refetched after jwks_cache_ttl, or at most every 10 seconds for a token signed with an unknown key.
  • Refresh token. By default it stays in an httponly, secure, SameSite=Strict cookie scoped to auth_path, out of reach of JavaScript. secure cookies need HTTPS; disable it only for local development.
  • Admin credentials. Prefer a service account with manage-users and view-realm to a master-realm administrator in production.

Development

uv sync --group dev
uv run ruff check .
uv run ruff format --check .
uv run pytest
uv build
uv run twine check --strict dist/*

The tests start a fake Keycloak on aiohttp.web (tests/fake_keycloak.py), so they run real HTTP against the admin client and token validation without a Keycloak instance.

See CONTRIBUTING.md for contribution guidelines, CHANGELOG.md for user-visible changes, and the release guide for the release process.

License

Distributed under the MIT License.

Metadata

Release files for fastapi-keycloak-admin 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-keycloak-admin 0.1.0
File Size Uploaded Provenance Actions
fastapi_keycloak_admin-0.1.0.tar.gz 41.6 kB With provenance Details for fastapi_keycloak_admin-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-keycloak-admin 0.1.0
File Interpreter ABI Platform Actions
fastapi_keycloak_admin-0.1.0-py3-none-any.whl Python 3 none any Details for fastapi_keycloak_admin-0.1.0-py3-none-any.whl

Total release size: 83.2 kB

Release files / fastapi_keycloak_admin-0.1.0.tar.gz

Download URL fastapi_keycloak_admin-0.1.0.tar.gz
Size 41.6 kB
Tags Source
SHA-256 checksum
How to use checksums
5531d7428564780e8e25f6473200ea83c5b2305b6129f7a19bb79075a47b1b5d
BLAKE2b-256 checksum
How to use checksums
7d965845551c9e4f7f238d646e5440cc315a5811fe641f8ce7462a70289e2eb1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 28, 2026.

Transparency log

Release files / fastapi_keycloak_admin-0.1.0-py3-none-any.whl

Download URL fastapi_keycloak_admin-0.1.0-py3-none-any.whl
Size 41.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
32907c32ce1413a979b3bee8df93bd2b4503bcc53da61ac4fd42c8a81109891f
BLAKE2b-256 checksum
How to use checksums
7166de4f7228bb2d42389cf76e402188e9b111f8fc5679f63d30c56e6c9e6bde
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 28, 2026.

Transparency log

Security for fastapi-keycloak-admin 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fastapi_keycloak_admin-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 28, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page