Metadata-Version: 2.4
Name: fastapi-keycloak-admin
Version: 0.1.0
Summary: Keycloak authentication, account and user administration for FastAPI applications
Keywords: authentication,fastapi,keycloak,oauth2,oidc
Author: Alexander Korolev
Author-email: Alexander Korolev <alexkorolex@bk.ru>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: AsyncIO
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Dist: aiohttp>=3.9
Requires-Dist: click>=8.1
Requires-Dist: fastapi>=0.115
Requires-Dist: pyjwt[crypto]>=2.8
Requires-Python: >=3.12
Project-URL: Changelog, https://github.com/alexkorolex/fastapi_keycloak_admin/blob/main/CHANGELOG.md
Project-URL: Documentation, https://github.com/alexkorolex/fastapi_keycloak_admin#readme
Project-URL: Issues, https://github.com/alexkorolex/fastapi_keycloak_admin/issues
Project-URL: Repository, https://github.com/alexkorolex/fastapi_keycloak_admin
Description-Content-Type: text/markdown

# fastapi-keycloak-admin

[![PyPI](https://img.shields.io/pypi/v/fastapi-keycloak-admin)](https://pypi.org/project/fastapi-keycloak-admin/)
[![Python](https://img.shields.io/pypi/pyversions/fastapi-keycloak-admin)](https://pypi.org/project/fastapi-keycloak-admin/)
[![CI](https://github.com/alexkorolex/fastapi_keycloak_admin/actions/workflows/ci.yml/badge.svg)](https://github.com/alexkorolex/fastapi_keycloak_admin/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/alexkorolex/fastapi_keycloak_admin/blob/main/LICENSE)

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](https://github.com/alexkorolex/fastapi_keycloak_admin#security-notes) before using it in production.

It is the FastAPI counterpart of
[litestar-keycloak-admin](https://github.com/alexkorolex/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](https://github.com/alexkorolex/fastapi_keycloak_admin#installation) ·
[Quick start](https://github.com/alexkorolex/fastapi_keycloak_admin#quick-start) ·
[Keycloak setup](https://github.com/alexkorolex/fastapi_keycloak_admin#keycloak-setup) ·
[Protecting routes](https://github.com/alexkorolex/fastapi_keycloak_admin#protecting-routes) ·
[Login flow](https://github.com/alexkorolex/fastapi_keycloak_admin#login-flow) ·
[Endpoints](https://github.com/alexkorolex/fastapi_keycloak_admin#endpoints) ·
[Errors](https://github.com/alexkorolex/fastapi_keycloak_admin#errors) ·
[Configuration](https://github.com/alexkorolex/fastapi_keycloak_admin#configuration) ·
[Command line](https://github.com/alexkorolex/fastapi_keycloak_admin#command-line) ·
[Using the client](https://github.com/alexkorolex/fastapi_keycloak_admin#using-the-client-in-your-own-code) ·
[Public API](https://github.com/alexkorolex/fastapi_keycloak_admin#public-api) ·
[Security notes](https://github.com/alexkorolex/fastapi_keycloak_admin#security-notes)

## Installation

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

```bash
# 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

```python
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](https://github.com/alexkorolex/fastapi_keycloak_admin#endpoints));
- an *Authorize* button in `/docs` that takes an access token.

A minimal local environment looks like this:

```dotenv
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:

```json
{
  "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`:

```python
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:

```python
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](https://github.com/alexkorolex/fastapi_keycloak_admin#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`:

```python
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:

  ```python
  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:

```json
{
  "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:

```python
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](https://github.com/alexkorolex/fastapi_keycloak_admin#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](https://github.com/alexkorolex/fastapi_keycloak_admin#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`:

```bash
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:

```python
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](https://github.com/alexkorolex/fastapi_keycloak_admin#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](https://semver.org/); while it is in `0.x`, a minor
release may contain breaking changes, which are listed in the
[changelog](https://github.com/alexkorolex/fastapi_keycloak_admin/blob/main/CHANGELOG.md).

## 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

```bash
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](https://github.com/alexkorolex/fastapi_keycloak_admin/blob/main/CONTRIBUTING.md)
for contribution guidelines,
[CHANGELOG.md](https://github.com/alexkorolex/fastapi_keycloak_admin/blob/main/CHANGELOG.md)
for user-visible changes, and the
[release guide](https://github.com/alexkorolex/fastapi_keycloak_admin/blob/main/docs/releasing.md)
for the release process.

## License

Distributed under the
[MIT License](https://github.com/alexkorolex/fastapi_keycloak_admin/blob/main/LICENSE).
