Auth API

This module contains the built-in authentication middleware, the OIDC token-validation engine, and the injectable JWKS cache. The configuration dataclasses MCPAuthConfig and OIDCProviderConfig are documented under Types.

MCPAuthBackend

class litestar_mcp.auth.MCPAuthBackend[source]

Bases: AbstractAuthenticationMiddleware

Authenticate bearer tokens via OIDC providers + optional custom validator.

Registration:

from litestar import Litestar
from litestar.middleware import DefineMiddleware
from litestar_mcp import MCPAuthBackend, OIDCProviderConfig

app = Litestar(
    middleware=[
        DefineMiddleware(
            MCPAuthBackend,
            providers=[OIDCProviderConfig(issuer="https://idp", audience="api")],
            user_resolver=lambda claims, app: MyUser(sub=claims["sub"]),
        ),
    ],
)

Apps that already ship their own AbstractAuthenticationMiddleware (DMA's IAPAuthenticationMiddleware, Litestar's JWT backends, etc.) do not need this — MCP route handlers read request.user / request.auth populated by whichever middleware the app installed.

header_name / token_prefix make the built-in validation engine usable behind identity proxies that inject a verified JWT in a non-standard header. For Google Cloud IAP the assertion arrives raw (no Bearer prefix) in X-Goog-IAP-JWT-Assertion:

DefineMiddleware(
    MCPAuthBackend,
    providers=[OIDCProviderConfig(issuer="https://cloud.google.com/iap", audience="/projects/.../apps/...")],
    header_name="X-Goog-IAP-JWT-Assertion",
    token_prefix="",
)
__init__(app, providers=(), token_validator=None, user_resolver=None, header_name='Authorization', token_prefix='Bearer ', exclude=None, exclude_from_auth_key='exclude_from_auth', exclude_http_methods=None, scopes=None)[source]

Initialize AbstractAuthenticationMiddleware.

Parameters:
  • app -- An ASGIApp, this value is the next ASGI handler to call in the middleware stack.

  • exclude -- A pattern or list of patterns to skip in the authentication middleware.

  • exclude_from_auth_key -- An identifier to use on routes to disable authentication for a particular route.

  • exclude_http_methods -- A sequence of http methods that do not require authentication.

  • scopes -- ASGI scopes processed by the authentication middleware.

async authenticate_request(connection)[source]

Receive the http connection and return an AuthenticationResult.

Notes

  • This method must be overridden by subclasses.

Parameters:

connection (ASGIConnection[typing.Any, typing.Any, typing.Any, typing.Any]) -- An ASGIConnection instance.

Raises:

NotAuthorizedException | PermissionDeniedException -- if authentication fails.

Return type:

AuthenticationResult

Returns:

An instance of AuthenticationResult.

create_oidc_validator

litestar_mcp.auth.create_oidc_validator(issuer, audience, *, jwks_uri=None, algorithms=('RS256',), clock_skew=30, jwks_cache_ttl=3600, jwks_cache=None, on_validation_error=None)[source]

Build an async token validator that verifies bearer tokens against an OIDC IdP.

If jwks_uri is omitted, the validator auto-discovers it from {issuer}/.well-known/openid-configuration. The JWKS document is cached in-memory with the given TTL.

Parameters:
  • issuer (str) -- Expected iss claim and discovery base URL.

  • audience (str) -- Expected aud claim.

  • jwks_uri (Optional[str]) -- Optional explicit JWKS endpoint (overrides discovery).

  • algorithms (tuple[str, ...]) -- Allowed JWS algorithms.

  • clock_skew (int) -- Tolerance in seconds for exp / iat / nbf checks.

  • jwks_cache_ttl (int) -- JWKS / discovery document TTL in seconds.

  • jwks_cache (Optional[JWKSCache]) -- Optional shared JWKSCache instance. When None the process-wide default cache is used.

  • on_validation_error (Optional[Callable[[str, BaseException], None | Awaitable[None]]]) -- Observability hook invoked on failure.

Return type:

Callable[[str], Awaitable[dict[str, Any] | None]]

Returns:

An async callable suitable for MCPAuthBackend's token_validator constructor argument.

Example

>>> from litestar.middleware import DefineMiddleware
>>> from litestar_mcp import MCPAuthBackend, create_oidc_validator
>>> validator = create_oidc_validator(
...     "https://company.okta.com",
...     "api://mcp-tools",
...     clock_skew=60,
... )
>>> middleware = DefineMiddleware(MCPAuthBackend, token_validator=validator)

TokenValidator

litestar_mcp.auth.TokenValidator

alias of Callable[[str], Awaitable[dict[str, Any] | None]]

JWKSCache

class litestar_mcp.auth.JWKSCache[source]

Bases: Protocol

Shared JWKS / OIDC discovery document cache contract.

get returns the cached document (fresh, within TTL) or None. set stamps an expiry at insertion time using ttl seconds. invalidate drops a single entry; implementations may treat invalidate as a no-op for unknown URLs.

__init__(*args, **kwargs)

DefaultJWKSCache

class litestar_mcp.auth.DefaultJWKSCache[source]

Bases: object

In-process TTL cache with per-URL write locks.

Preserves the 0.4.0 module-global cache semantics exactly — the public interface makes them injectable so applications can share one cache across their own auth stack and litestar-mcp's OIDC validator.

__init__()[source]
clear()[source]

Drop every cached entry and all per-URL locks.

Return type:

None