Skip to content

API Reference

Public API of litestar-keycloak. Import from the top-level package:

from litestar_keycloak import (
    KeycloakPlugin,
    KeycloakConfig,
    TokenLocation,
    KeycloakUser,
    TokenPayload,
    CurrentUser,
    CurrentTokenPayload,
    CurrentRawToken,
    OptionalCurrentUser,
    OptionalTokenPayload,
    OptionalRawToken,
    ServiceTokens,
    ServiceTokenClient,
    require_roles,
    require_client_roles,
    require_groups,
    require_scopes,
    require_acr,
    require_recent_auth,
    require_user,
    MatchStrategy,
)

Plugin and config

litestar_keycloak.plugin.KeycloakPlugin

Bases: InitPluginProtocol

Litestar plugin that integrates Keycloak authentication.

Usage::

from litestar import Litestar
from litestar_keycloak import KeycloakPlugin, KeycloakConfig

app = Litestar(
    route_handlers=[...],
    plugins=[KeycloakPlugin(
        KeycloakConfig(
            server_url="https://keycloak.example.com",
            realm="my-realm",
            client_id="my-app",
        )
    )],
)
Source code in src/litestar_keycloak/plugin.py
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
class KeycloakPlugin(InitPluginProtocol):
    """Litestar plugin that integrates Keycloak authentication.

    Usage::

        from litestar import Litestar
        from litestar_keycloak import KeycloakPlugin, KeycloakConfig

        app = Litestar(
            route_handlers=[...],
            plugins=[KeycloakPlugin(
                KeycloakConfig(
                    server_url="https://keycloak.example.com",
                    realm="my-realm",
                    client_id="my-app",
                )
            )],
        )
    """

    __slots__ = ("_config", "_http", "_jwks_cache", "_service_tokens", "_verifier")

    def __init__(self, config: KeycloakConfig) -> None:
        self._config = config
        self._http = KeycloakHttpClient(config.http_timeout)
        self._jwks_cache = JWKSCache(
            jwks_url=config.jwks_url,
            ttl=config.jwks_cache_ttl,
            http=self._http,
        )
        introspector = (
            TokenIntrospector(config, self._http)
            if config.token_introspection
            else None
        )
        self._verifier = TokenVerifier(config, self._jwks_cache, introspector)

    def on_app_init(self, app_config: AppConfig) -> AppConfig:
        """Hook called by Litestar during application startup.

        Registers:
        - Authentication middleware (bearer token extraction + validation)
        - Exception handlers (``KeycloakError`` hierarchy -> HTTP responses)
        - DI providers (``current_user``, ``token_payload``, ``raw_token``)
        - OIDC routes (when ``include_routes`` is ``True``)
        - Lifespan handlers to warm the JWKS cache on startup (best-effort) and
          close the shared HTTP client on shutdown
        """
        # -- auth middleware -----------------------------------------------
        # Appended (not inserted at 0) so it runs *after* any app-level session
        # middleware — required for callback_response_mode="redirect", where the
        # token is read from the session the session middleware populates.
        middleware_cls = create_auth_middleware(
            self._config,
            self._verifier,
            refresh=self._refresh_session_tokens
            if self._config.session_auto_refresh
            else None,
        )
        app_config.middleware.append(
            DefineMiddleware(
                middleware_cls,
                exclude=self._config.exclude_auth_patterns,
                exclude_from_auth_key=self._config.exclude_opt_key,
            )
        )

        # -- exception handlers --------------------------------------------
        app_config.exception_handlers = cast(
            "Any",
            {
                **exception_handlers,
                **app_config.exception_handlers,
            },
        )

        # -- DI providers --------------------------------------------------
        # Built here rather than in __init__ so plugin subclasses that replace
        # __init__ (e.g. test doubles) still get one.
        self._service_tokens = ServiceTokenClient(self._config, self._http)
        app_config.dependencies = {
            **build_dependencies(),
            "service_tokens": Provide(
                self._provide_service_tokens, sync_to_thread=False
            ),
            **app_config.dependencies,
        }

        if self._config.backchannel_logout and _per_process_store(
            app_config.stores, self._config.logout_store
        ):
            logger.warning(
                "backchannel_logout records logouts in a per-process memory store; "
                "register a shared store (e.g. Redis) under logout_store=%r when the "
                "app runs as several instances, or a logout reaches only one of them",
                self._config.logout_store,
            )

        # -- OIDC routes ---------------------------------------------------
        if self._config.include_routes:
            controller = build_auth_controller(self._config, self._http, self._verifier)
            app_config.route_handlers.append(controller)

        # -- lifespan: warm JWKS on startup, close HTTP client on shutdown --
        app_config.on_startup.append(self._on_startup)
        app_config.on_shutdown.append(self._on_shutdown)

        return app_config

    @property
    def service_tokens(self) -> ServiceTokenClient:
        """Outbound token client, for code outside handlers (available once the
        app is initialised; handlers declare ``service_tokens: ServiceTokens``)."""
        return self._service_tokens

    def _provide_service_tokens(self) -> ServiceTokenClient:
        return self._service_tokens

    async def _refresh_session_tokens(self, refresh_token: str) -> dict[str, Any]:
        return await _refresh_token(self._config, refresh_token, http=self._http)

    async def _on_startup(self) -> None:
        """Warm the JWKS cache so the first request doesn't pay fetch latency.

        Best-effort: if Keycloak is unreachable at boot the warm-up is skipped
        rather than aborting application startup — the cache refetches lazily on
        the first request (which returns 502 until Keycloak is reachable).
        """
        try:
            await self._jwks_cache.warm()
        except JWKSFetchError as exc:
            logger.warning(
                "JWKS warm-up skipped (Keycloak unreachable at startup): %s. "
                "Keys will be fetched on the first request.",
                exc,
            )

    async def _on_shutdown(self) -> None:
        """Close the shared HTTP client so its connections are released."""
        await self._http.close()

__slots__ = ('_config', '_http', '_jwks_cache', '_service_tokens', '_verifier') class-attribute instance-attribute

_config = config instance-attribute

_http = KeycloakHttpClient(config.http_timeout) instance-attribute

_jwks_cache = JWKSCache(jwks_url=(config.jwks_url), ttl=(config.jwks_cache_ttl), http=(self._http)) instance-attribute

_verifier = TokenVerifier(config, self._jwks_cache, introspector) instance-attribute

service_tokens property

Outbound token client, for code outside handlers (available once the app is initialised; handlers declare service_tokens: ServiceTokens).

__init__(config)

Source code in src/litestar_keycloak/plugin.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def __init__(self, config: KeycloakConfig) -> None:
    self._config = config
    self._http = KeycloakHttpClient(config.http_timeout)
    self._jwks_cache = JWKSCache(
        jwks_url=config.jwks_url,
        ttl=config.jwks_cache_ttl,
        http=self._http,
    )
    introspector = (
        TokenIntrospector(config, self._http)
        if config.token_introspection
        else None
    )
    self._verifier = TokenVerifier(config, self._jwks_cache, introspector)

_on_shutdown() async

Close the shared HTTP client so its connections are released.

Source code in src/litestar_keycloak/plugin.py
177
178
179
async def _on_shutdown(self) -> None:
    """Close the shared HTTP client so its connections are released."""
    await self._http.close()

_on_startup() async

Warm the JWKS cache so the first request doesn't pay fetch latency.

Best-effort: if Keycloak is unreachable at boot the warm-up is skipped rather than aborting application startup — the cache refetches lazily on the first request (which returns 502 until Keycloak is reachable).

Source code in src/litestar_keycloak/plugin.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
async def _on_startup(self) -> None:
    """Warm the JWKS cache so the first request doesn't pay fetch latency.

    Best-effort: if Keycloak is unreachable at boot the warm-up is skipped
    rather than aborting application startup — the cache refetches lazily on
    the first request (which returns 502 until Keycloak is reachable).
    """
    try:
        await self._jwks_cache.warm()
    except JWKSFetchError as exc:
        logger.warning(
            "JWKS warm-up skipped (Keycloak unreachable at startup): %s. "
            "Keys will be fetched on the first request.",
            exc,
        )

_provide_service_tokens()

Source code in src/litestar_keycloak/plugin.py
155
156
def _provide_service_tokens(self) -> ServiceTokenClient:
    return self._service_tokens

_refresh_session_tokens(refresh_token) async

Source code in src/litestar_keycloak/plugin.py
158
159
async def _refresh_session_tokens(self, refresh_token: str) -> dict[str, Any]:
    return await _refresh_token(self._config, refresh_token, http=self._http)

on_app_init(app_config)

Hook called by Litestar during application startup.

Registers: - Authentication middleware (bearer token extraction + validation) - Exception handlers (KeycloakError hierarchy -> HTTP responses) - DI providers (current_user, token_payload, raw_token) - OIDC routes (when include_routes is True) - Lifespan handlers to warm the JWKS cache on startup (best-effort) and close the shared HTTP client on shutdown

Source code in src/litestar_keycloak/plugin.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def on_app_init(self, app_config: AppConfig) -> AppConfig:
    """Hook called by Litestar during application startup.

    Registers:
    - Authentication middleware (bearer token extraction + validation)
    - Exception handlers (``KeycloakError`` hierarchy -> HTTP responses)
    - DI providers (``current_user``, ``token_payload``, ``raw_token``)
    - OIDC routes (when ``include_routes`` is ``True``)
    - Lifespan handlers to warm the JWKS cache on startup (best-effort) and
      close the shared HTTP client on shutdown
    """
    # -- auth middleware -----------------------------------------------
    # Appended (not inserted at 0) so it runs *after* any app-level session
    # middleware — required for callback_response_mode="redirect", where the
    # token is read from the session the session middleware populates.
    middleware_cls = create_auth_middleware(
        self._config,
        self._verifier,
        refresh=self._refresh_session_tokens
        if self._config.session_auto_refresh
        else None,
    )
    app_config.middleware.append(
        DefineMiddleware(
            middleware_cls,
            exclude=self._config.exclude_auth_patterns,
            exclude_from_auth_key=self._config.exclude_opt_key,
        )
    )

    # -- exception handlers --------------------------------------------
    app_config.exception_handlers = cast(
        "Any",
        {
            **exception_handlers,
            **app_config.exception_handlers,
        },
    )

    # -- DI providers --------------------------------------------------
    # Built here rather than in __init__ so plugin subclasses that replace
    # __init__ (e.g. test doubles) still get one.
    self._service_tokens = ServiceTokenClient(self._config, self._http)
    app_config.dependencies = {
        **build_dependencies(),
        "service_tokens": Provide(
            self._provide_service_tokens, sync_to_thread=False
        ),
        **app_config.dependencies,
    }

    if self._config.backchannel_logout and _per_process_store(
        app_config.stores, self._config.logout_store
    ):
        logger.warning(
            "backchannel_logout records logouts in a per-process memory store; "
            "register a shared store (e.g. Redis) under logout_store=%r when the "
            "app runs as several instances, or a logout reaches only one of them",
            self._config.logout_store,
        )

    # -- OIDC routes ---------------------------------------------------
    if self._config.include_routes:
        controller = build_auth_controller(self._config, self._http, self._verifier)
        app_config.route_handlers.append(controller)

    # -- lifespan: warm JWKS on startup, close HTTP client on shutdown --
    app_config.on_startup.append(self._on_startup)
    app_config.on_shutdown.append(self._on_shutdown)

    return app_config

litestar_keycloak.config.KeycloakConfig dataclass

Immutable configuration for the Keycloak plugin.

Only server_url, realm, and client_id are required. Everything else has sensible defaults suitable for a typical confidential-client setup with RS256-signed JWTs.

Example::

KeycloakConfig(
    server_url="https://keycloak.example.com",
    realm="my-realm",
    client_id="my-app",
    client_secret="s3cret",
)
Source code in src/litestar_keycloak/config.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
@dataclass(frozen=True, slots=True)
class KeycloakConfig:
    """Immutable configuration for the Keycloak plugin.

    Only ``server_url``, ``realm``, and ``client_id`` are required.
    Everything else has sensible defaults suitable for a typical
    confidential-client setup with RS256-signed JWTs.

    Example::

        KeycloakConfig(
            server_url="https://keycloak.example.com",
            realm="my-realm",
            client_id="my-app",
            client_secret="s3cret",
        )
    """

    # -- connection --------------------------------------------------------
    server_url: str
    """Base Keycloak URL without trailing slash (e.g. ``https://kc.example.com``)."""

    realm: str
    """Keycloak realm name."""

    client_id: str
    """OIDC client identifier registered in the realm."""

    client_secret: str | None = None
    """Client secret for confidential clients.  ``None`` for public clients."""

    # -- token -------------------------------------------------------------
    token_location: TokenLocation = TokenLocation.HEADER
    """Where to read the bearer token from: ``Authorization`` header or a cookie."""

    cookie_name: str = "access_token"
    """Cookie name the middleware reads when ``token_location`` is ``COOKIE``.
    The plugin never *sets* this cookie — how the token gets there is the
    application's responsibility (see ``callback_response_mode``)."""

    cookie_secure: bool = True
    """``Secure`` attribute on the OAuth ``state`` cookie the routes set.  Set
    ``False`` for plain-HTTP local development."""

    cookie_samesite: Literal["lax", "strict", "none"] = "lax"
    """``SameSite`` attribute on the OAuth ``state`` cookie the routes set."""

    algorithms: tuple[str, ...] = ("RS256",)
    """Accepted JWT signing algorithms.  Add e.g. ``"ES256"`` or ``"EdDSA"`` when
    the realm signs with an EC or Ed25519 key provider."""

    leeway: int = 0
    """Seconds of clock skew tolerated when checking ``exp``, ``nbf`` and
    ``iat``.  Set a few seconds if the app and Keycloak clocks may drift."""

    scopes: tuple[str, ...] = ("openid",)
    """Scopes requested during the authorization code flow."""

    # -- revocation --------------------------------------------------------
    token_introspection: bool = False
    """Ask Keycloak (RFC 7662) whether each locally valid token is still active.

    A JWT stays valid until ``exp`` even after its session is logged out or
    its user disabled; introspection catches that on the next request, at the
    cost of one call to Keycloak per request (see
    ``introspection_cache_ttl``).  Requires ``client_secret``: Keycloak only
    answers authenticated confidential clients."""

    introspection_cache_ttl: int = 0
    """Seconds to reuse a positive introspection result for the same token.
    ``0`` (default) introspects every request, so a revocation takes effect
    immediately; a positive value trades that delay for fewer calls."""

    # -- JWKS --------------------------------------------------------------
    jwks_cache_ttl: int = 3600
    """How long (seconds) to cache the JWKS before re-fetching."""

    # -- routes ------------------------------------------------------------
    include_routes: bool = False
    """Mount ``/auth/login``, ``/callback``, ``/logout``, ``/refresh`` routes."""

    auth_prefix: str = "/auth"
    """URL prefix for the optional OIDC route group."""

    redirect_uri: str | None = None
    """OAuth2 redirect URI for the authorization code flow.
    Required when ``include_routes`` is ``True``."""

    callback_response_mode: Literal["json", "redirect"] = "json"
    """What ``/auth/callback`` does after exchanging the code:

    - ``"json"`` (default): return the token response as JSON — the SPA/BFF
      stores the access token and sends it as ``Authorization: Bearer``.
    - ``"redirect"``: store the tokens in the **server-side session** and redirect
      to ``post_login_redirect_uri`` — for server-rendered apps.  Requires
      Litestar session middleware (e.g. ``ServerSideSessionConfig``); the auth
      middleware then reads the access token from the session."""

    post_login_redirect_uri: str = "/"
    """Where ``redirect``-mode login redirects after storing tokens in the session."""

    post_logout_redirect_uri: str | None = None
    """Where ``redirect``-mode logout redirects.  Returns JSON status when ``None``."""

    use_pkce: bool = False
    """Send a PKCE ``S256`` code challenge on login (RFC 7636) and prove it on
    the code exchange.  Required for public clients; harmless and recommended
    for confidential ones.  Keycloak can enforce it per client (Advanced →
    "Proof Key for Code Exchange Code Challenge Method")."""

    session_auto_refresh: bool = False
    """In ``"redirect"`` mode, renew an expired access token from the session
    with its refresh token instead of answering 401, and write the new tokens
    back to the session.  A refresh Keycloak rejects (session ended, refresh
    token expired) answers 401; the stale tokens stay in the session until the
    next login replaces them."""

    session_binding: bool = False
    """In ``"redirect"`` mode, bind the session's tokens to an HttpOnly cookie
    set at login and accept them only alongside it.  Litestar keeps the session
    id across login, so without it an attacker who planted a session id in the
    victim's browser shares the victim's login (session fixation).  The cookie
    lasts until the browser closes; sessions from before it was switched on
    must log in again."""

    backchannel_logout: bool = False
    """Mount ``POST {auth_prefix}/backchannel-logout`` for Keycloak's OIDC
    back-channel logout, and refuse tokens from sessions it reports ended.  Set
    the client's *Backchannel logout URL* in Keycloak to this endpoint."""

    logout_store: str = "keycloak_logout"
    """Name of the Litestar store recording back-channel logouts.  The default
    is an in-memory store per process; register a shared store (e.g. Redis)
    under this name when the app runs as several instances."""

    validate_id_token: bool = False
    """Send an OIDC ``nonce`` on login and, in the callback, require the
    returned ID token to be valid for this client and carry that nonce.
    Requires ``"openid"`` in ``scopes``."""

    # -- advanced ----------------------------------------------------------
    audience: str | None = None
    """Expected ``aud`` claim.  Defaults to ``client_id`` when ``None``."""

    expected_issuer: str | None = None
    """Expected ``iss`` claim.  Defaults to ``realm_url`` when ``None``.  Set this
    when Keycloak's frontend/hostname URL differs from ``server_url`` (e.g. behind
    a reverse proxy), so token issuer validation matches the value Keycloak signs."""

    optional_audiences: frozenset[str] = field(default_factory=frozenset)
    """Additional audiences to accept (e.g. service client IDs)."""

    strict_audience: bool = False
    """Accept a token only if its ``aud`` contains an accepted audience.
    ``False`` (default) also accepts a token whose ``azp`` is accepted, because
    Keycloak access tokens often lack the client's own audience.  Before setting
    ``True``, add a Keycloak Audience mapper (``oidc-audience-mapper``) to the
    clients that call this API."""

    require_sub: bool = False
    """Refuse a token without a ``sub`` claim.  ``False`` (default) falls back
    to ``preferred_username``, which Keycloak 25+ hands out instead of ``sub``
    when a client lacks the ``basic`` scope; a username can be reassigned, so
    data keyed by it may reach the next holder of the name."""

    expected_token_type: str | None = "Bearer"
    """Required payload ``typ`` claim.  ``"Bearer"`` (default) rejects Keycloak
    ID and Refresh tokens presented as access tokens.  Set to ``None`` to disable
    the check (e.g. non-Keycloak OIDC providers that omit ``typ``)."""

    http_timeout: int = 10
    """Timeout in seconds for outgoing HTTP calls to Keycloak."""

    excluded_paths: frozenset[str] = field(default_factory=frozenset)
    """Exact request paths that skip authentication entirely (e.g. ``/health``).
    Matched literally — for prefixes or subtrees use ``exclude_patterns``."""

    exclude_patterns: tuple[str, ...] = ()
    """Regex patterns whose matching request paths skip authentication.

    Unlike ``excluded_paths`` (exact match), these cover prefixes and subtrees,
    e.g. ``("^/public/", "^/docs")``.  Patterns are matched unanchored against
    the path, so anchor with ``^`` to match from the start."""

    exclude_opt_key: str = "exclude_from_auth"
    """Route-handler ``opt`` key for per-handler opt-out, e.g.
    ``@get("/open", exclude_from_auth=True)``."""

    optional_auth_opt_key: str = "optional_auth"
    """Route-handler ``opt`` key for optional authentication, e.g.
    ``@get("/feed", optional_auth=True)``: a request without a token proceeds
    anonymously (``current_user`` is ``None``), while a token that is present
    must still be valid.  Annotate such handlers with ``OptionalCurrentUser``."""

    groups_claim: str = "groups"
    """Token claim holding the user's groups, as configured on Keycloak's Group
    Membership mapper.  Note that the built-in ``microprofile-jwt`` scope puts
    realm *roles* into a claim of the same name."""

    # -- derived properties ------------------------------------------------

    @property
    def realm_url(self) -> str:
        """``{server_url}/realms/{realm}`` — base for all OIDC endpoints."""
        return f"{self.server_url.rstrip('/')}/realms/{self.realm}"

    @property
    def issuer(self) -> str:
        """Expected ``iss`` claim value.

        Defaults to ``realm_url``.  Set ``expected_issuer`` when Keycloak issues
        tokens under a different base (its configured frontend/hostname URL),
        which is common behind a reverse proxy where the public URL differs from
        the ``server_url`` the backend uses to reach Keycloak.
        """
        if self.expected_issuer is not None:
            return self.expected_issuer
        return self.realm_url

    @property
    def jwks_url(self) -> str:
        """JSON Web Key Set endpoint URL."""
        return f"{self.realm_url}/protocol/openid-connect/certs"

    @property
    def authorization_url(self) -> str:
        """Authorization endpoint for the code flow."""
        return f"{self.realm_url}/protocol/openid-connect/auth"

    @property
    def token_url(self) -> str:
        """Token endpoint for code exchange and refresh."""
        return f"{self.realm_url}/protocol/openid-connect/token"

    @property
    def logout_url(self) -> str:
        """End-session endpoint."""
        return f"{self.realm_url}/protocol/openid-connect/logout"

    @property
    def introspection_url(self) -> str:
        """Token introspection endpoint (RFC 7662)."""
        return f"{self.realm_url}/protocol/openid-connect/token/introspect"

    @property
    def effective_audience(self) -> str:
        """Primary audience for JWT validation (explicit or client_id)."""
        return self.audience if self.audience is not None else self.client_id

    @property
    def accepted_audiences(self) -> frozenset[str]:
        """All audiences accepted for JWT validation (primary + optional_audiences)."""
        return frozenset({self.effective_audience}) | self.optional_audiences

    @property
    def effective_excluded_paths(self) -> frozenset[str]:
        """Paths that skip auth: excluded_paths plus auth routes when include_routes."""
        if not self.include_routes:
            return self.excluded_paths
        auth_paths = {
            f"{self.auth_prefix}/login",
            f"{self.auth_prefix}/callback",
            f"{self.auth_prefix}/logout",
            f"{self.auth_prefix}/refresh",
        }
        if self.backchannel_logout:
            auth_paths.add(f"{self.auth_prefix}/backchannel-logout")
        return self.excluded_paths | auth_paths

    @property
    def exclude_auth_patterns(self) -> list[str] | None:
        """Regex patterns for request paths that bypass the auth middleware.

        Exact ``excluded_paths`` (and the auth routes when ``include_routes``) are
        anchored to ``^…$``; ``exclude_patterns`` are used verbatim.  Returns
        ``None`` when nothing is excluded — an empty pattern list would compile to
        an empty regex that greedily matches every path.
        """
        patterns = [
            f"^{re.escape(path)}$" for path in sorted(self.effective_excluded_paths)
        ]
        patterns.extend(self.exclude_patterns)
        return patterns or None

    def __post_init__(self) -> None:
        if self.include_routes and self.redirect_uri is None:
            raise ValueError("redirect_uri is required when include_routes is True")
        if self.jwks_cache_ttl < 0:
            raise ValueError("jwks_cache_ttl must be non-negative")
        if self.http_timeout <= 0:
            raise ValueError("http_timeout must be positive")
        if self.leeway < 0:
            raise ValueError("leeway must be non-negative")
        if self.token_introspection and self.client_secret is None:
            raise ValueError("token_introspection requires client_secret")
        if self.introspection_cache_ttl < 0:
            raise ValueError("introspection_cache_ttl must be non-negative")
        if self.session_auto_refresh and self.callback_response_mode != "redirect":
            raise ValueError(
                'session_auto_refresh requires callback_response_mode="redirect"'
            )
        if self.session_binding and self.callback_response_mode != "redirect":
            raise ValueError(
                'session_binding requires callback_response_mode="redirect"'
            )
        if self.backchannel_logout and not self.include_routes:
            raise ValueError("backchannel_logout requires include_routes=True")
        if self.validate_id_token and "openid" not in self.scopes:
            raise ValueError('validate_id_token requires "openid" in scopes')
        if self.cookie_samesite == "none" and not self.cookie_secure:
            # Browsers drop such cookies, so every login would fail its state check.
            raise ValueError('cookie_samesite="none" requires cookie_secure=True')
        if not _AUTH_PREFIX_RE.fullmatch(self.auth_prefix):
            raise ValueError(
                f"auth_prefix must look like '/auth' (no trailing slash), "
                f"got {self.auth_prefix!r}"
            )
        self._check_algorithms()
        if self.optional_audiences and not self.strict_audience:
            logger.warning(
                "optional_audiences without strict_audience=True also accepts any "
                "token whose azp is one of them, whatever its aud: %s",
                ", ".join(sorted(self.optional_audiences)),
            )

    def _check_algorithms(self) -> None:
        unusable = [
            alg
            for alg in self.algorithms
            if not alg.startswith(_PUBLIC_KEY_ALG_PREFIXES)
        ]
        if len(unusable) == len(self.algorithms):
            raise ValueError(
                "algorithms must include a public-key algorithm (RS*, PS*, ES*, "
                f"EdDSA), got {self.algorithms!r}"
            )
        if unusable:
            logger.warning(
                "algorithms %s cannot verify Keycloak tokens; tokens using them "
                "are refused",
                ", ".join(unusable),
            )

accepted_audiences property

All audiences accepted for JWT validation (primary + optional_audiences).

algorithms = ('RS256',) class-attribute instance-attribute

Accepted JWT signing algorithms. Add e.g. "ES256" or "EdDSA" when the realm signs with an EC or Ed25519 key provider.

audience = None class-attribute instance-attribute

Expected aud claim. Defaults to client_id when None.

auth_prefix = '/auth' class-attribute instance-attribute

URL prefix for the optional OIDC route group.

authorization_url property

Authorization endpoint for the code flow.

backchannel_logout = False class-attribute instance-attribute

Mount POST {auth_prefix}/backchannel-logout for Keycloak's OIDC back-channel logout, and refuse tokens from sessions it reports ended. Set the client's Backchannel logout URL in Keycloak to this endpoint.

callback_response_mode = 'json' class-attribute instance-attribute

What /auth/callback does after exchanging the code:

  • "json" (default): return the token response as JSON — the SPA/BFF stores the access token and sends it as Authorization: Bearer.
  • "redirect": store the tokens in the server-side session and redirect to post_login_redirect_uri — for server-rendered apps. Requires Litestar session middleware (e.g. ServerSideSessionConfig); the auth middleware then reads the access token from the session.

client_id instance-attribute

OIDC client identifier registered in the realm.

client_secret = None class-attribute instance-attribute

Client secret for confidential clients. None for public clients.

cookie_name = 'access_token' class-attribute instance-attribute

Cookie name the middleware reads when token_location is COOKIE. The plugin never sets this cookie — how the token gets there is the application's responsibility (see callback_response_mode).

cookie_samesite = 'lax' class-attribute instance-attribute

SameSite attribute on the OAuth state cookie the routes set.

cookie_secure = True class-attribute instance-attribute

Secure attribute on the OAuth state cookie the routes set. Set False for plain-HTTP local development.

effective_audience property

Primary audience for JWT validation (explicit or client_id).

effective_excluded_paths property

Paths that skip auth: excluded_paths plus auth routes when include_routes.

exclude_auth_patterns property

Regex patterns for request paths that bypass the auth middleware.

Exact excluded_paths (and the auth routes when include_routes) are anchored to ^…$; exclude_patterns are used verbatim. Returns None when nothing is excluded — an empty pattern list would compile to an empty regex that greedily matches every path.

exclude_opt_key = 'exclude_from_auth' class-attribute instance-attribute

Route-handler opt key for per-handler opt-out, e.g. @get("/open", exclude_from_auth=True).

exclude_patterns = () class-attribute instance-attribute

Regex patterns whose matching request paths skip authentication.

Unlike excluded_paths (exact match), these cover prefixes and subtrees, e.g. ("^/public/", "^/docs"). Patterns are matched unanchored against the path, so anchor with ^ to match from the start.

excluded_paths = field(default_factory=frozenset) class-attribute instance-attribute

Exact request paths that skip authentication entirely (e.g. /health). Matched literally — for prefixes or subtrees use exclude_patterns.

expected_issuer = None class-attribute instance-attribute

Expected iss claim. Defaults to realm_url when None. Set this when Keycloak's frontend/hostname URL differs from server_url (e.g. behind a reverse proxy), so token issuer validation matches the value Keycloak signs.

expected_token_type = 'Bearer' class-attribute instance-attribute

Required payload typ claim. "Bearer" (default) rejects Keycloak ID and Refresh tokens presented as access tokens. Set to None to disable the check (e.g. non-Keycloak OIDC providers that omit typ).

groups_claim = 'groups' class-attribute instance-attribute

Token claim holding the user's groups, as configured on Keycloak's Group Membership mapper. Note that the built-in microprofile-jwt scope puts realm roles into a claim of the same name.

http_timeout = 10 class-attribute instance-attribute

Timeout in seconds for outgoing HTTP calls to Keycloak.

include_routes = False class-attribute instance-attribute

Mount /auth/login, /callback, /logout, /refresh routes.

introspection_cache_ttl = 0 class-attribute instance-attribute

Seconds to reuse a positive introspection result for the same token. 0 (default) introspects every request, so a revocation takes effect immediately; a positive value trades that delay for fewer calls.

introspection_url property

Token introspection endpoint (RFC 7662).

issuer property

Expected iss claim value.

Defaults to realm_url. Set expected_issuer when Keycloak issues tokens under a different base (its configured frontend/hostname URL), which is common behind a reverse proxy where the public URL differs from the server_url the backend uses to reach Keycloak.

jwks_cache_ttl = 3600 class-attribute instance-attribute

How long (seconds) to cache the JWKS before re-fetching.

jwks_url property

JSON Web Key Set endpoint URL.

leeway = 0 class-attribute instance-attribute

Seconds of clock skew tolerated when checking exp, nbf and iat. Set a few seconds if the app and Keycloak clocks may drift.

logout_store = 'keycloak_logout' class-attribute instance-attribute

Name of the Litestar store recording back-channel logouts. The default is an in-memory store per process; register a shared store (e.g. Redis) under this name when the app runs as several instances.

logout_url property

End-session endpoint.

optional_audiences = field(default_factory=frozenset) class-attribute instance-attribute

Additional audiences to accept (e.g. service client IDs).

optional_auth_opt_key = 'optional_auth' class-attribute instance-attribute

Route-handler opt key for optional authentication, e.g. @get("/feed", optional_auth=True): a request without a token proceeds anonymously (current_user is None), while a token that is present must still be valid. Annotate such handlers with OptionalCurrentUser.

post_login_redirect_uri = '/' class-attribute instance-attribute

Where redirect-mode login redirects after storing tokens in the session.

post_logout_redirect_uri = None class-attribute instance-attribute

Where redirect-mode logout redirects. Returns JSON status when None.

realm instance-attribute

Keycloak realm name.

realm_url property

{server_url}/realms/{realm} — base for all OIDC endpoints.

redirect_uri = None class-attribute instance-attribute

OAuth2 redirect URI for the authorization code flow. Required when include_routes is True.

require_sub = False class-attribute instance-attribute

Refuse a token without a sub claim. False (default) falls back to preferred_username, which Keycloak 25+ hands out instead of sub when a client lacks the basic scope; a username can be reassigned, so data keyed by it may reach the next holder of the name.

scopes = ('openid',) class-attribute instance-attribute

Scopes requested during the authorization code flow.

server_url instance-attribute

Base Keycloak URL without trailing slash (e.g. https://kc.example.com).

session_auto_refresh = False class-attribute instance-attribute

In "redirect" mode, renew an expired access token from the session with its refresh token instead of answering 401, and write the new tokens back to the session. A refresh Keycloak rejects (session ended, refresh token expired) answers 401; the stale tokens stay in the session until the next login replaces them.

session_binding = False class-attribute instance-attribute

In "redirect" mode, bind the session's tokens to an HttpOnly cookie set at login and accept them only alongside it. Litestar keeps the session id across login, so without it an attacker who planted a session id in the victim's browser shares the victim's login (session fixation). The cookie lasts until the browser closes; sessions from before it was switched on must log in again.

strict_audience = False class-attribute instance-attribute

Accept a token only if its aud contains an accepted audience. False (default) also accepts a token whose azp is accepted, because Keycloak access tokens often lack the client's own audience. Before setting True, add a Keycloak Audience mapper (oidc-audience-mapper) to the clients that call this API.

token_introspection = False class-attribute instance-attribute

Ask Keycloak (RFC 7662) whether each locally valid token is still active.

A JWT stays valid until exp even after its session is logged out or its user disabled; introspection catches that on the next request, at the cost of one call to Keycloak per request (see introspection_cache_ttl). Requires client_secret: Keycloak only answers authenticated confidential clients.

token_location = TokenLocation.HEADER class-attribute instance-attribute

Where to read the bearer token from: Authorization header or a cookie.

token_url property

Token endpoint for code exchange and refresh.

use_pkce = False class-attribute instance-attribute

Send a PKCE S256 code challenge on login (RFC 7636) and prove it on the code exchange. Required for public clients; harmless and recommended for confidential ones. Keycloak can enforce it per client (Advanced → "Proof Key for Code Exchange Code Challenge Method").

validate_id_token = False class-attribute instance-attribute

Send an OIDC nonce on login and, in the callback, require the returned ID token to be valid for this client and carry that nonce. Requires "openid" in scopes.

__init__(server_url, realm, client_id, client_secret=None, token_location=TokenLocation.HEADER, cookie_name='access_token', cookie_secure=True, cookie_samesite='lax', algorithms=('RS256',), leeway=0, scopes=('openid',), token_introspection=False, introspection_cache_ttl=0, jwks_cache_ttl=3600, include_routes=False, auth_prefix='/auth', redirect_uri=None, callback_response_mode='json', post_login_redirect_uri='/', post_logout_redirect_uri=None, use_pkce=False, session_auto_refresh=False, session_binding=False, backchannel_logout=False, logout_store='keycloak_logout', validate_id_token=False, audience=None, expected_issuer=None, optional_audiences=frozenset(), strict_audience=False, require_sub=False, expected_token_type='Bearer', http_timeout=10, excluded_paths=frozenset(), exclude_patterns=(), exclude_opt_key='exclude_from_auth', optional_auth_opt_key='optional_auth', groups_claim='groups')

__post_init__()

Source code in src/litestar_keycloak/config.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
def __post_init__(self) -> None:
    if self.include_routes and self.redirect_uri is None:
        raise ValueError("redirect_uri is required when include_routes is True")
    if self.jwks_cache_ttl < 0:
        raise ValueError("jwks_cache_ttl must be non-negative")
    if self.http_timeout <= 0:
        raise ValueError("http_timeout must be positive")
    if self.leeway < 0:
        raise ValueError("leeway must be non-negative")
    if self.token_introspection and self.client_secret is None:
        raise ValueError("token_introspection requires client_secret")
    if self.introspection_cache_ttl < 0:
        raise ValueError("introspection_cache_ttl must be non-negative")
    if self.session_auto_refresh and self.callback_response_mode != "redirect":
        raise ValueError(
            'session_auto_refresh requires callback_response_mode="redirect"'
        )
    if self.session_binding and self.callback_response_mode != "redirect":
        raise ValueError(
            'session_binding requires callback_response_mode="redirect"'
        )
    if self.backchannel_logout and not self.include_routes:
        raise ValueError("backchannel_logout requires include_routes=True")
    if self.validate_id_token and "openid" not in self.scopes:
        raise ValueError('validate_id_token requires "openid" in scopes')
    if self.cookie_samesite == "none" and not self.cookie_secure:
        # Browsers drop such cookies, so every login would fail its state check.
        raise ValueError('cookie_samesite="none" requires cookie_secure=True')
    if not _AUTH_PREFIX_RE.fullmatch(self.auth_prefix):
        raise ValueError(
            f"auth_prefix must look like '/auth' (no trailing slash), "
            f"got {self.auth_prefix!r}"
        )
    self._check_algorithms()
    if self.optional_audiences and not self.strict_audience:
        logger.warning(
            "optional_audiences without strict_audience=True also accepts any "
            "token whose azp is one of them, whatever its aud: %s",
            ", ".join(sorted(self.optional_audiences)),
        )

_check_algorithms()

Source code in src/litestar_keycloak/config.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
def _check_algorithms(self) -> None:
    unusable = [
        alg
        for alg in self.algorithms
        if not alg.startswith(_PUBLIC_KEY_ALG_PREFIXES)
    ]
    if len(unusable) == len(self.algorithms):
        raise ValueError(
            "algorithms must include a public-key algorithm (RS*, PS*, ES*, "
            f"EdDSA), got {self.algorithms!r}"
        )
    if unusable:
        logger.warning(
            "algorithms %s cannot verify Keycloak tokens; tokens using them "
            "are refused",
            ", ".join(unusable),
        )

litestar_keycloak.config.TokenLocation

Bases: Enum

Where the plugin looks for the access token on incoming requests.

Source code in src/litestar_keycloak/config.py
27
28
29
30
31
class TokenLocation(enum.Enum):
    """Where the plugin looks for the access token on incoming requests."""

    HEADER = "header"
    COOKIE = "cookie"

COOKIE = 'cookie' class-attribute instance-attribute

HEADER = 'header' class-attribute instance-attribute

Models

litestar_keycloak.models.KeycloakUser dataclass

High-level identity object injected into route handlers.

Wraps TokenPayload and exposes a flattened, ergonomic API so handlers don't need to know about raw JWT claim structures::

@get("/me")
async def me(current_user: CurrentUser) -> dict:
    return {"name": current_user.name, "roles": current_user.realm_roles}
Source code in src/litestar_keycloak/models.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
@dataclass(frozen=True, slots=True)
class KeycloakUser:
    """High-level identity object injected into route handlers.

    Wraps ``TokenPayload`` and exposes a flattened, ergonomic API so
    handlers don't need to know about raw JWT claim structures::

        @get("/me")
        async def me(current_user: CurrentUser) -> dict:
            return {"name": current_user.name, "roles": current_user.realm_roles}
    """

    sub: str
    """Keycloak user ID."""

    preferred_username: str | None = None
    email: str | None = None
    email_verified: bool = False
    given_name: str | None = None
    family_name: str | None = None
    name: str | None = None

    realm_roles: frozenset[str] = field(default_factory=frozenset)
    """All realm-level roles."""

    client_roles: dict[str, frozenset[str]] = field(default_factory=dict)
    """Client roles keyed by client ID."""

    scopes: frozenset[str] = field(default_factory=frozenset)
    """Token scopes as a set."""

    raw: TokenPayload | None = None
    """Full token payload for advanced use cases."""

    iss: str | None = None
    """Issuer.  Together with ``sub`` it identifies the user unambiguously."""

    azp: str | None = None
    """Client the token was issued to."""

    groups: frozenset[str] = field(default_factory=frozenset)
    """Group names from the group-membership claim (see ``groups_claim``)."""

    acr: str | None = None
    """Authentication context class of the login."""

    auth_time: int | None = None
    """When the user last actively authenticated (Unix epoch seconds)."""

    sid: str | None = None
    """Keycloak session ID."""

    is_service_account: bool = False
    """``True`` for a client_credentials token, which acts as a client, not a user."""

    def has_role(self, role: str) -> bool:
        """Check if the user holds a realm role."""
        return role in self.realm_roles

    def has_client_role(self, client_id: str, role: str) -> bool:
        """Check if the user holds a role for a specific client."""
        return role in self.client_roles.get(client_id, frozenset())

    def has_scope(self, scope: str) -> bool:
        """Check if the token carries a specific scope."""
        return scope in self.scopes

    def has_group(self, group: str) -> bool:
        """Check if the user belongs to a group (as named in the token)."""
        return group in self.groups

    @classmethod
    def from_token(
        cls, payload: TokenPayload, *, groups_claim: str = "groups"
    ) -> KeycloakUser:
        """Construct from a validated ``TokenPayload``."""
        client_roles = {
            client_id: frozenset(access.get("roles", []))
            for client_id, access in payload.resource_access.items()
        }
        groups = payload.extra.get(groups_claim)
        return cls(
            sub=payload.sub,
            preferred_username=payload.preferred_username,
            email=payload.email,
            email_verified=payload.email_verified,
            given_name=payload.given_name,
            family_name=payload.family_name,
            name=payload.name,
            realm_roles=payload.realm_roles,
            client_roles=client_roles,
            scopes=payload.scopes,
            raw=payload,
            iss=payload.iss,
            azp=payload.azp,
            groups=frozenset(groups) if isinstance(groups, list) else frozenset(),
            acr=payload.acr,
            auth_time=payload.auth_time,
            sid=payload.sid,
            # The service_account client scope adds client_id; Keycloak < 24
            # used a clientId claim instead.
            is_service_account=any(
                k in payload.extra for k in ("client_id", "clientId")
            ),
        )

acr = None class-attribute instance-attribute

Authentication context class of the login.

auth_time = None class-attribute instance-attribute

When the user last actively authenticated (Unix epoch seconds).

azp = None class-attribute instance-attribute

Client the token was issued to.

client_roles = field(default_factory=dict) class-attribute instance-attribute

Client roles keyed by client ID.

email = None class-attribute instance-attribute

email_verified = False class-attribute instance-attribute

family_name = None class-attribute instance-attribute

given_name = None class-attribute instance-attribute

groups = field(default_factory=frozenset) class-attribute instance-attribute

Group names from the group-membership claim (see groups_claim).

is_service_account = False class-attribute instance-attribute

True for a client_credentials token, which acts as a client, not a user.

iss = None class-attribute instance-attribute

Issuer. Together with sub it identifies the user unambiguously.

name = None class-attribute instance-attribute

preferred_username = None class-attribute instance-attribute

raw = None class-attribute instance-attribute

Full token payload for advanced use cases.

realm_roles = field(default_factory=frozenset) class-attribute instance-attribute

All realm-level roles.

scopes = field(default_factory=frozenset) class-attribute instance-attribute

Token scopes as a set.

sid = None class-attribute instance-attribute

Keycloak session ID.

sub instance-attribute

Keycloak user ID.

__init__(sub, preferred_username=None, email=None, email_verified=False, given_name=None, family_name=None, name=None, realm_roles=frozenset(), client_roles=dict(), scopes=frozenset(), raw=None, iss=None, azp=None, groups=frozenset(), acr=None, auth_time=None, sid=None, is_service_account=False)

from_token(payload, *, groups_claim='groups') classmethod

Construct from a validated TokenPayload.

Source code in src/litestar_keycloak/models.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
@classmethod
def from_token(
    cls, payload: TokenPayload, *, groups_claim: str = "groups"
) -> KeycloakUser:
    """Construct from a validated ``TokenPayload``."""
    client_roles = {
        client_id: frozenset(access.get("roles", []))
        for client_id, access in payload.resource_access.items()
    }
    groups = payload.extra.get(groups_claim)
    return cls(
        sub=payload.sub,
        preferred_username=payload.preferred_username,
        email=payload.email,
        email_verified=payload.email_verified,
        given_name=payload.given_name,
        family_name=payload.family_name,
        name=payload.name,
        realm_roles=payload.realm_roles,
        client_roles=client_roles,
        scopes=payload.scopes,
        raw=payload,
        iss=payload.iss,
        azp=payload.azp,
        groups=frozenset(groups) if isinstance(groups, list) else frozenset(),
        acr=payload.acr,
        auth_time=payload.auth_time,
        sid=payload.sid,
        # The service_account client scope adds client_id; Keycloak < 24
        # used a clientId claim instead.
        is_service_account=any(
            k in payload.extra for k in ("client_id", "clientId")
        ),
    )

has_client_role(client_id, role)

Check if the user holds a role for a specific client.

Source code in src/litestar_keycloak/models.py
202
203
204
def has_client_role(self, client_id: str, role: str) -> bool:
    """Check if the user holds a role for a specific client."""
    return role in self.client_roles.get(client_id, frozenset())

has_group(group)

Check if the user belongs to a group (as named in the token).

Source code in src/litestar_keycloak/models.py
210
211
212
def has_group(self, group: str) -> bool:
    """Check if the user belongs to a group (as named in the token)."""
    return group in self.groups

has_role(role)

Check if the user holds a realm role.

Source code in src/litestar_keycloak/models.py
198
199
200
def has_role(self, role: str) -> bool:
    """Check if the user holds a realm role."""
    return role in self.realm_roles

has_scope(scope)

Check if the token carries a specific scope.

Source code in src/litestar_keycloak/models.py
206
207
208
def has_scope(self, scope: str) -> bool:
    """Check if the token carries a specific scope."""
    return scope in self.scopes

litestar_keycloak.models.TokenPayload dataclass

Decoded and validated JWT claims.

Mirrors the standard OIDC claims plus Keycloak-specific role structures. Constructed by the token module after successful validation — fields are guaranteed to satisfy all configured checks (issuer, audience, expiry, algorithm) by the time this object exists.

Source code in src/litestar_keycloak/models.py
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
@dataclass(frozen=True, slots=True)
class TokenPayload:
    """Decoded and validated JWT claims.

    Mirrors the standard OIDC claims plus Keycloak-specific role
    structures.  Constructed by the ``token`` module after successful
    validation — fields are guaranteed to satisfy all configured checks
    (issuer, audience, expiry, algorithm) by the time this object exists.
    """

    # -- standard OIDC claims ---------------------------------------------
    sub: str
    """Subject identifier (Keycloak user ID, typically a UUID)."""

    iss: str
    """Issuer URL (``{server_url}/realms/{realm}``)."""

    aud: str | list[str]
    """Audience — single client ID or a list when multiple audiences are present."""

    exp: int
    """Expiration timestamp (Unix epoch seconds)."""

    iat: int
    """Issued-at timestamp (Unix epoch seconds)."""

    # -- optional standard claims ------------------------------------------
    azp: str | None = None
    """Authorized party — the client that requested the token."""

    scope: str = ""
    """Space-delimited scope string (e.g. ``"openid profile email"``)."""

    jti: str | None = None
    """Unique token identifier."""

    typ: str | None = None
    """Token type (typically ``"Bearer"``)."""

    # -- Keycloak-specific claims ------------------------------------------
    preferred_username: str | None = None
    email: str | None = None
    email_verified: bool = False
    given_name: str | None = None
    family_name: str | None = None
    name: str | None = None

    realm_access: dict[str, Any] = field(default_factory=dict)
    """Raw ``realm_access`` claim (e.g. ``{"roles": ["admin", "user"]}``)."""

    resource_access: dict[str, Any] = field(default_factory=dict)
    """Raw ``resource_access`` claim keyed by client ID."""

    # -- extra claims catchall ---------------------------------------------
    extra: dict[str, Any] = field(default_factory=dict)
    """Any remaining claims not explicitly modeled above."""

    # -- convenience -------------------------------------------------------

    @property
    def realm_roles(self) -> frozenset[str]:
        """Realm-level roles extracted from ``realm_access.roles``."""
        return frozenset(self.realm_access.get("roles", []))

    def client_roles(self, client_id: str) -> frozenset[str]:
        """Roles for a specific client from ``resource_access``."""
        access = self.resource_access.get(client_id, {})
        return frozenset(access.get("roles", []))

    @property
    def scopes(self) -> frozenset[str]:
        """Scope string split into a set for O(1) membership tests."""
        return frozenset(self.scope.split()) if self.scope else frozenset()

    # Read from ``extra`` rather than declared as fields: these claims landed
    # there before they were modelled, and moving them would break readers.
    @property
    def acr(self) -> str | None:
        """Authentication context class (e.g. ``"1"`` password, ``"2"`` with OTP)."""
        value = self.extra.get("acr")
        return str(value) if value is not None else None

    @property
    def auth_time(self) -> int | None:
        """When the user last actively authenticated (Unix epoch seconds)."""
        value = self.extra.get("auth_time")
        return int(value) if value is not None else None

    @property
    def sid(self) -> str | None:
        """Keycloak session ID shared by all tokens of one login session."""
        value = self.extra.get("sid")
        return str(value) if value is not None else None

    @property
    def expires_at(self) -> datetime:
        """``exp`` as a timezone-aware UTC datetime."""
        return datetime.fromtimestamp(self.exp, tz=UTC)

    @property
    def issued_at(self) -> datetime:
        """``iat`` as a timezone-aware UTC datetime."""
        return datetime.fromtimestamp(self.iat, tz=UTC)

    @classmethod
    def from_claims(cls, claims: dict[str, Any]) -> TokenPayload:
        """Build a ``TokenPayload`` from a raw decoded JWT dict.

        Known fields are mapped to explicit attributes; everything else
        lands in ``extra`` so no claim is silently dropped.
        Keycloak may omit ``aud``; fall back to ``azp`` when building.
        """
        # Normalize aud (Keycloak sometimes omits it; use azp as fallback)
        normalized = dict(claims)
        if not normalized.get("aud"):
            normalized["aud"] = normalized.get("azp") or ""
        # Some OIDC providers omit "sub" from access tokens;
        # falling back to preferred_username
        if "sub" not in normalized or normalized.get("sub") is None:
            normalized["sub"] = normalized.get("preferred_username") or ""
        known_fields = {f.name for f in cls.__dataclass_fields__.values()} - {"extra"}
        known = {k: v for k, v in normalized.items() if k in known_fields}
        extra = {k: v for k, v in normalized.items() if k not in known_fields}
        return cls(**known, extra=extra)

acr property

Authentication context class (e.g. "1" password, "2" with OTP).

aud instance-attribute

Audience — single client ID or a list when multiple audiences are present.

auth_time property

When the user last actively authenticated (Unix epoch seconds).

azp = None class-attribute instance-attribute

Authorized party — the client that requested the token.

email = None class-attribute instance-attribute

email_verified = False class-attribute instance-attribute

exp instance-attribute

Expiration timestamp (Unix epoch seconds).

expires_at property

exp as a timezone-aware UTC datetime.

extra = field(default_factory=dict) class-attribute instance-attribute

Any remaining claims not explicitly modeled above.

family_name = None class-attribute instance-attribute

given_name = None class-attribute instance-attribute

iat instance-attribute

Issued-at timestamp (Unix epoch seconds).

iss instance-attribute

Issuer URL ({server_url}/realms/{realm}).

issued_at property

iat as a timezone-aware UTC datetime.

jti = None class-attribute instance-attribute

Unique token identifier.

name = None class-attribute instance-attribute

preferred_username = None class-attribute instance-attribute

realm_access = field(default_factory=dict) class-attribute instance-attribute

Raw realm_access claim (e.g. {"roles": ["admin", "user"]}).

realm_roles property

Realm-level roles extracted from realm_access.roles.

resource_access = field(default_factory=dict) class-attribute instance-attribute

Raw resource_access claim keyed by client ID.

scope = '' class-attribute instance-attribute

Space-delimited scope string (e.g. "openid profile email").

scopes property

Scope string split into a set for O(1) membership tests.

sid property

Keycloak session ID shared by all tokens of one login session.

sub instance-attribute

Subject identifier (Keycloak user ID, typically a UUID).

typ = None class-attribute instance-attribute

Token type (typically "Bearer").

__init__(sub, iss, aud, exp, iat, azp=None, scope='', jti=None, typ=None, preferred_username=None, email=None, email_verified=False, given_name=None, family_name=None, name=None, realm_access=dict(), resource_access=dict(), extra=dict())

client_roles(client_id)

Roles for a specific client from resource_access.

Source code in src/litestar_keycloak/models.py
81
82
83
84
def client_roles(self, client_id: str) -> frozenset[str]:
    """Roles for a specific client from ``resource_access``."""
    access = self.resource_access.get(client_id, {})
    return frozenset(access.get("roles", []))

from_claims(claims) classmethod

Build a TokenPayload from a raw decoded JWT dict.

Known fields are mapped to explicit attributes; everything else lands in extra so no claim is silently dropped. Keycloak may omit aud; fall back to azp when building.

Source code in src/litestar_keycloak/models.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
@classmethod
def from_claims(cls, claims: dict[str, Any]) -> TokenPayload:
    """Build a ``TokenPayload`` from a raw decoded JWT dict.

    Known fields are mapped to explicit attributes; everything else
    lands in ``extra`` so no claim is silently dropped.
    Keycloak may omit ``aud``; fall back to ``azp`` when building.
    """
    # Normalize aud (Keycloak sometimes omits it; use azp as fallback)
    normalized = dict(claims)
    if not normalized.get("aud"):
        normalized["aud"] = normalized.get("azp") or ""
    # Some OIDC providers omit "sub" from access tokens;
    # falling back to preferred_username
    if "sub" not in normalized or normalized.get("sub") is None:
        normalized["sub"] = normalized.get("preferred_username") or ""
    known_fields = {f.name for f in cls.__dataclass_fields__.values()} - {"extra"}
    known = {k: v for k, v in normalized.items() if k in known_fields}
    extra = {k: v for k, v in normalized.items() if k not in known_fields}
    return cls(**known, extra=extra)

Handler annotations

Annotate handler parameters with these; the parameter names must stay current_user, token_payload and raw_token, since injection is name-based.

Annotation Injects
CurrentUser KeycloakUser
CurrentTokenPayload TokenPayload
CurrentRawToken str
OptionalCurrentUser KeycloakUser \| None — for optional-auth routes
OptionalTokenPayload TokenPayload \| None
OptionalRawToken str \| None
ServiceTokens ServiceTokenClient (parameter name service_tokens) — outbound tokens, see Service-to-service

Outbound tokens

litestar_keycloak.service_tokens.ServiceTokenClient

Issues access tokens for outbound calls with this app's client credentials.

Source code in src/litestar_keycloak/service_tokens.py
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
class ServiceTokenClient:
    """Issues access tokens for outbound calls with this app's client credentials."""

    def __init__(self, config: KeycloakConfig, http: KeycloakHttpClient) -> None:
        self._config = config
        self._http = http
        self._cached: dict[str | None, tuple[str, float]] = {}
        self._lock = asyncio.Lock()

    async def client_token(self, *, scope: str | None = None) -> str:
        """An access token for this client itself (client_credentials grant).

        Cached per *scope* until shortly before it expires; concurrent callers
        share one grant.
        """
        cached = self._fresh(scope)
        if cached is not None:
            return cached
        async with self._lock:
            # Another coroutine may have renewed it while we waited on the lock.
            cached = self._fresh(scope)
            if cached is not None:
                return cached
            form = {"grant_type": "client_credentials"}
            if scope:
                form["scope"] = scope
            body = await self._grant("client_credentials", form)
            token = str(body["access_token"])
            self._cached[scope] = (token, _renew_at(body.get("expires_in")))
            return token

    async def exchange(
        self, subject_token: str, *, audience: str, scope: str | None = None
    ) -> str:
        """Exchange *subject_token* for an access token addressed to *audience*.

        Keycloak requires this client to have *Standard token exchange* on, the
        subject token's ``aud`` to include this client, and *audience* to be
        available to it (e.g. through an Audience mapper).  Not cached: each
        exchanged token belongs to one caller.
        """
        form = {
            "grant_type": _TOKEN_EXCHANGE_GRANT,
            "subject_token": subject_token,
            "subject_token_type": _ACCESS_TOKEN_TYPE,
            "audience": audience,
        }
        if scope:
            form["scope"] = scope
        body = await self._grant("token-exchange", form)
        return str(body["access_token"])

    def _fresh(self, scope: str | None) -> str | None:
        entry = self._cached.get(scope)
        if entry is not None and time.monotonic() < entry[1]:
            return entry[0]
        return None

    async def _grant(self, grant: str, form: dict[str, str]) -> dict[str, Any]:
        if self._config.client_secret is None:
            raise ValueError(
                "service tokens require client_secret (a confidential client)"
            )
        credentials = {
            "client_id": self._config.client_id,
            "client_secret": self._config.client_secret,
        }
        # grant_type first, then credentials, then the grant's own parameters.
        data = {"grant_type": form.pop("grant_type"), **credentials, **form}
        try:
            status, body = await self._http.post_form_status(
                self._config.token_url, data
            )
        except (aiohttp.ClientError, OSError) as exc:
            raise ServiceTokenError(grant) from exc
        if status != 200 or "access_token" not in body:
            error = ServiceTokenError(
                grant,
                status=status,
                error=body.get("error"),
                error_description=body.get("error_description"),
            )
            logger.warning(
                "%s (HTTP %s): %s", error, status, error.error_description or "-"
            )
            raise error
        return body

_cached = {} instance-attribute

_config = config instance-attribute

_http = http instance-attribute

_lock = asyncio.Lock() instance-attribute

__init__(config, http)

Source code in src/litestar_keycloak/service_tokens.py
43
44
45
46
47
def __init__(self, config: KeycloakConfig, http: KeycloakHttpClient) -> None:
    self._config = config
    self._http = http
    self._cached: dict[str | None, tuple[str, float]] = {}
    self._lock = asyncio.Lock()

_fresh(scope)

Source code in src/litestar_keycloak/service_tokens.py
92
93
94
95
96
def _fresh(self, scope: str | None) -> str | None:
    entry = self._cached.get(scope)
    if entry is not None and time.monotonic() < entry[1]:
        return entry[0]
    return None

_grant(grant, form) async

Source code in src/litestar_keycloak/service_tokens.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
async def _grant(self, grant: str, form: dict[str, str]) -> dict[str, Any]:
    if self._config.client_secret is None:
        raise ValueError(
            "service tokens require client_secret (a confidential client)"
        )
    credentials = {
        "client_id": self._config.client_id,
        "client_secret": self._config.client_secret,
    }
    # grant_type first, then credentials, then the grant's own parameters.
    data = {"grant_type": form.pop("grant_type"), **credentials, **form}
    try:
        status, body = await self._http.post_form_status(
            self._config.token_url, data
        )
    except (aiohttp.ClientError, OSError) as exc:
        raise ServiceTokenError(grant) from exc
    if status != 200 or "access_token" not in body:
        error = ServiceTokenError(
            grant,
            status=status,
            error=body.get("error"),
            error_description=body.get("error_description"),
        )
        logger.warning(
            "%s (HTTP %s): %s", error, status, error.error_description or "-"
        )
        raise error
    return body

client_token(*, scope=None) async

An access token for this client itself (client_credentials grant).

Cached per scope until shortly before it expires; concurrent callers share one grant.

Source code in src/litestar_keycloak/service_tokens.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
async def client_token(self, *, scope: str | None = None) -> str:
    """An access token for this client itself (client_credentials grant).

    Cached per *scope* until shortly before it expires; concurrent callers
    share one grant.
    """
    cached = self._fresh(scope)
    if cached is not None:
        return cached
    async with self._lock:
        # Another coroutine may have renewed it while we waited on the lock.
        cached = self._fresh(scope)
        if cached is not None:
            return cached
        form = {"grant_type": "client_credentials"}
        if scope:
            form["scope"] = scope
        body = await self._grant("client_credentials", form)
        token = str(body["access_token"])
        self._cached[scope] = (token, _renew_at(body.get("expires_in")))
        return token

exchange(subject_token, *, audience, scope=None) async

Exchange subject_token for an access token addressed to audience.

Keycloak requires this client to have Standard token exchange on, the subject token's aud to include this client, and audience to be available to it (e.g. through an Audience mapper). Not cached: each exchanged token belongs to one caller.

Source code in src/litestar_keycloak/service_tokens.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
async def exchange(
    self, subject_token: str, *, audience: str, scope: str | None = None
) -> str:
    """Exchange *subject_token* for an access token addressed to *audience*.

    Keycloak requires this client to have *Standard token exchange* on, the
    subject token's ``aud`` to include this client, and *audience* to be
    available to it (e.g. through an Audience mapper).  Not cached: each
    exchanged token belongs to one caller.
    """
    form = {
        "grant_type": _TOKEN_EXCHANGE_GRANT,
        "subject_token": subject_token,
        "subject_token_type": _ACCESS_TOKEN_TYPE,
        "audience": audience,
    }
    if scope:
        form["scope"] = scope
    body = await self._grant("token-exchange", form)
    return str(body["access_token"])

Guards

litestar_keycloak.guards.MatchStrategy

Bases: Enum

How multiple required values are evaluated.

Source code in src/litestar_keycloak/guards.py
34
35
36
37
38
39
40
41
class MatchStrategy(enum.Enum):
    """How multiple required values are evaluated."""

    ALL = "all"
    """User must hold **every** required role/scope (default)."""

    ANY = "any"
    """User must hold **at least one** of the required roles/scopes."""

ALL = 'all' class-attribute instance-attribute

User must hold every required role/scope (default).

ANY = 'any' class-attribute instance-attribute

User must hold at least one of the required roles/scopes.

litestar_keycloak.guards.require_roles(*roles, strategy=MatchStrategy.ALL)

Guard factory that enforces realm-level roles.

Parameters:

Name Type Description Default
*roles str

One or more role names the user must hold.

()
strategy MatchStrategy

ALL (default) requires every role; ANY requires at least one.

ALL

Example::

@get("/admin", guards=[require_roles("admin")])
async def admin_panel() -> dict: ...

@get("/staff", guards=[require_roles(
    "admin", "manager", strategy=MatchStrategy.ANY)])
async def staff_area() -> dict: ...
Source code in src/litestar_keycloak/guards.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def require_roles(
    *roles: str,
    strategy: MatchStrategy = MatchStrategy.ALL,
) -> Callable[..., None]:
    """Guard factory that enforces realm-level roles.

    Args:
        *roles: One or more role names the user must hold.
        strategy: ``ALL`` (default) requires every role;
                  ``ANY`` requires at least one.

    Example::

        @get("/admin", guards=[require_roles("admin")])
        async def admin_panel() -> dict: ...

        @get("/staff", guards=[require_roles(
            "admin", "manager", strategy=MatchStrategy.ANY)])
        async def staff_area() -> dict: ...
    """
    required = frozenset(roles)

    def guard(
        connection: ASGIConnection[Any, Any, Any, Any], _: BaseRouteHandler
    ) -> None:
        user = _resolve_user(connection)
        if strategy is MatchStrategy.ALL:
            satisfied = required <= user.realm_roles
        else:
            satisfied = bool(required & user.realm_roles)

        if not satisfied:
            raise InsufficientRoleError(required=required, actual=user.realm_roles)

    return guard

litestar_keycloak.guards.require_client_roles(client_id, *roles, strategy=MatchStrategy.ALL)

Guard factory that enforces client-level roles.

Parameters:

Name Type Description Default
client_id str

The Keycloak client whose roles are checked.

required
*roles str

One or more role names the user must hold for client_id.

()
strategy MatchStrategy

ALL (default) or ANY.

ALL

Example::

@get("/billing", guards=[require_client_roles("billing-service", "read")])
async def billing() -> dict: ...
Source code in src/litestar_keycloak/guards.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def require_client_roles(
    client_id: str,
    *roles: str,
    strategy: MatchStrategy = MatchStrategy.ALL,
) -> Callable[..., None]:
    """Guard factory that enforces client-level roles.

    Args:
        client_id: The Keycloak client whose roles are checked.
        *roles: One or more role names the user must hold for *client_id*.
        strategy: ``ALL`` (default) or ``ANY``.

    Example::

        @get("/billing", guards=[require_client_roles("billing-service", "read")])
        async def billing() -> dict: ...
    """
    required = frozenset(roles)

    def guard(
        connection: ASGIConnection[Any, Any, Any, Any], _: BaseRouteHandler
    ) -> None:
        user = _resolve_user(connection)
        actual = user.client_roles.get(client_id, frozenset())

        if strategy is MatchStrategy.ALL:
            satisfied = required <= actual
        else:
            satisfied = bool(required & actual)

        if not satisfied:
            raise InsufficientRoleError(required=required, actual=actual)

    return guard

litestar_keycloak.guards.require_groups(*groups, strategy=MatchStrategy.ALL)

Guard factory that enforces group membership.

Names are compared exactly as they appear in the token: with the Group Membership mapper's "Full group path" on, write "/parent/child".

Example::

@get("/ops", guards=[require_groups("ops", "sre", strategy=MatchStrategy.ANY)])
async def ops_panel() -> dict: ...
Source code in src/litestar_keycloak/guards.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def require_groups(
    *groups: str,
    strategy: MatchStrategy = MatchStrategy.ALL,
) -> Callable[..., None]:
    """Guard factory that enforces group membership.

    Names are compared exactly as they appear in the token: with the Group
    Membership mapper's "Full group path" on, write ``"/parent/child"``.

    Example::

        @get("/ops", guards=[require_groups("ops", "sre", strategy=MatchStrategy.ANY)])
        async def ops_panel() -> dict: ...
    """
    required = frozenset(groups)

    def guard(
        connection: ASGIConnection[Any, Any, Any, Any], _: BaseRouteHandler
    ) -> None:
        user = _resolve_user(connection)
        if strategy is MatchStrategy.ALL:
            satisfied = required <= user.groups
        else:
            satisfied = bool(required & user.groups)

        if not satisfied:
            raise InsufficientGroupError(required=required, actual=user.groups)

    return guard

litestar_keycloak.guards.require_scopes(*scopes, strategy=MatchStrategy.ALL)

Guard factory that enforces token scopes.

Parameters:

Name Type Description Default
*scopes str

One or more scope strings the token must carry.

()
strategy MatchStrategy

ALL (default) or ANY.

ALL

Example::

@get("/reports", guards=[require_scopes("reports:read")])
async def reports() -> dict: ...
Source code in src/litestar_keycloak/guards.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def require_scopes(
    *scopes: str,
    strategy: MatchStrategy = MatchStrategy.ALL,
) -> Callable[..., None]:
    """Guard factory that enforces token scopes.

    Args:
        *scopes: One or more scope strings the token must carry.
        strategy: ``ALL`` (default) or ``ANY``.

    Example::

        @get("/reports", guards=[require_scopes("reports:read")])
        async def reports() -> dict: ...
    """
    required = frozenset(scopes)

    def guard(
        connection: ASGIConnection[Any, Any, Any, Any], _: BaseRouteHandler
    ) -> None:
        user = _resolve_user(connection)

        if strategy is MatchStrategy.ALL:
            satisfied = required <= user.scopes
        else:
            satisfied = bool(required & user.scopes)

        if not satisfied:
            raise InsufficientScopeError(required=required, actual=user.scopes)

    return guard

litestar_keycloak.guards.require_acr(*acr_values)

Guard factory that requires one of acr_values as the login's acr.

On failure the client gets a 401 step-up challenge (RFC 9470) naming the acceptable values, so it can send the user back to Keycloak with acr_values to authenticate more strongly.

Example::

@post("/payments", guards=[require_acr("2")])
async def pay() -> dict: ...
Source code in src/litestar_keycloak/guards.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def require_acr(*acr_values: str) -> Callable[..., None]:
    """Guard factory that requires one of *acr_values* as the login's ``acr``.

    On failure the client gets a 401 step-up challenge (RFC 9470) naming the
    acceptable values, so it can send the user back to Keycloak with
    ``acr_values`` to authenticate more strongly.

    Example::

        @post("/payments", guards=[require_acr("2")])
        async def pay() -> dict: ...
    """
    accepted = frozenset(acr_values)

    def guard(
        connection: ASGIConnection[Any, Any, Any, Any], _: BaseRouteHandler
    ) -> None:
        user = _resolve_user(connection)
        if user.acr not in accepted:
            raise InsufficientAuthenticationError(acr_values=acr_values)

    return guard

litestar_keycloak.guards.require_recent_auth(max_age)

Guard factory that requires a login at most max_age seconds old.

Judged by the auth_time claim, which Keycloak adds only through the basic client scope and not for every grant (e.g. not for password grants); a token without it is rejected, since its login age is unknown.

Example::

@delete("/account", guards=[require_recent_auth(300)])
async def close_account() -> None: ...
Source code in src/litestar_keycloak/guards.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def require_recent_auth(max_age: int) -> Callable[..., None]:
    """Guard factory that requires a login at most *max_age* seconds old.

    Judged by the ``auth_time`` claim, which Keycloak adds only through the
    ``basic`` client scope and not for every grant (e.g. not for password
    grants); a token without it is rejected, since its login age is unknown.

    Example::

        @delete("/account", guards=[require_recent_auth(300)])
        async def close_account() -> None: ...
    """
    if max_age < 0:
        raise ValueError("max_age must be non-negative")

    def guard(
        connection: ASGIConnection[Any, Any, Any, Any], _: BaseRouteHandler
    ) -> None:
        user = _resolve_user(connection)
        if user.auth_time is None or time.time() - user.auth_time > max_age:
            raise InsufficientAuthenticationError(max_age=max_age)

    return guard

litestar_keycloak.guards.require_user(predicate, *, detail='Access denied')

Guard factory for a check the other guards cannot express.

predicate receives the KeycloakUser and returns whether access is allowed; on False the request gets a 403 with detail.

Example::

@get("/reports", guards=[require_user(
    lambda u: u.has_role("auditor") or u.has_group("finance"))])
async def reports() -> dict: ...
Source code in src/litestar_keycloak/guards.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def require_user(
    predicate: Callable[[KeycloakUser], bool],
    *,
    detail: str = "Access denied",
) -> Callable[..., None]:
    """Guard factory for a check the other guards cannot express.

    *predicate* receives the ``KeycloakUser`` and returns whether access is
    allowed; on ``False`` the request gets a 403 with *detail*.

    Example::

        @get("/reports", guards=[require_user(
            lambda u: u.has_role("auditor") or u.has_group("finance"))])
        async def reports() -> dict: ...
    """

    def guard(
        connection: ASGIConnection[Any, Any, Any, Any], _: BaseRouteHandler
    ) -> None:
        user = _resolve_user(connection)
        if not predicate(user):
            raise AuthorizationError(detail)

    return guard

Testing

litestar_keycloak.testing.create_test_token(sub='test-user-id', realm_roles=None, exp_offset=3600, iss=DEFAULT_ISSUER, aud=DEFAULT_AUDIENCE, typ='Bearer', headers=None, **extra_claims)

A JWT signed with the test key, shaped like a Keycloak access token.

exp_offset is seconds from now (negative for an expired token); extra_claims are added as is (e.g. groups=[...], resource_access={...}). typ=None leaves the typ claim out.

Source code in src/litestar_keycloak/testing.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def create_test_token(
    sub: str = "test-user-id",
    realm_roles: list[str] | None = None,
    exp_offset: int = 3600,
    iss: str = DEFAULT_ISSUER,
    aud: str = DEFAULT_AUDIENCE,
    typ: str | None = "Bearer",
    headers: dict[str, str] | None = None,
    **extra_claims: Any,
) -> str:
    """A JWT signed with the test key, shaped like a Keycloak access token.

    *exp_offset* is seconds from now (negative for an expired token);
    *extra_claims* are added as is (e.g. ``groups=[...]``,
    ``resource_access={...}``).  ``typ=None`` leaves the ``typ`` claim out.
    """
    now = int(time.time())
    payload = {
        "sub": sub,
        "iss": iss,
        "aud": aud,
        "iat": now,
        "exp": now + exp_offset,
        "realm_access": {"roles": realm_roles or ["user"]},
        **extra_claims,
    }
    if typ is not None:
        payload["typ"] = typ
    return jwt.encode(
        payload,
        _TEST_PRIVATE_KEY,
        algorithm="RS256",
        headers={"kid": DEFAULT_KID, **(headers or {})},
    )

litestar_keycloak.testing.MockKeycloakPlugin(server_url='http://localhost:8080', realm='test-realm', client_id='test-app', **kwargs)

A KeycloakPlugin that accepts create_test_token tokens.

kwargs are any other KeycloakConfig fields. Everything but key retrieval is the real plugin: guards, dependencies, routes and error responses behave as in production.

Source code in src/litestar_keycloak/testing.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def MockKeycloakPlugin(  # noqa: N802 - reads as the plugin class it stands in for
    server_url: str = "http://localhost:8080",
    realm: str = "test-realm",
    client_id: str = "test-app",
    **kwargs: Any,
) -> KeycloakPlugin:
    """A ``KeycloakPlugin`` that accepts ``create_test_token`` tokens.

    *kwargs* are any other ``KeycloakConfig`` fields.  Everything but key
    retrieval is the real plugin: guards, dependencies, routes and error
    responses behave as in production.
    """
    config = KeycloakConfig(
        server_url=server_url, realm=realm, client_id=client_id, **kwargs
    )
    cache = _InMemoryJWKSCache()
    verifier = TokenVerifier(config, cache)  # type: ignore[arg-type]

    class _MockPlugin(KeycloakPlugin):
        def __init__(self) -> None:
            self._config = config
            self._jwks_cache = cache  # type: ignore[assignment]
            self._verifier = verifier
            # Unused by the in-memory cache, but _on_shutdown closes it;
            # close() is a no-op when no session was ever opened.
            self._http = KeycloakHttpClient(config.http_timeout)

    return _MockPlugin()