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:
AbstractAuthenticationMiddlewareAuthenticate 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'sIAPAuthenticationMiddleware, Litestar's JWT backends, etc.) do not need this — MCP route handlers readrequest.user/request.authpopulated by whichever middleware the app installed.header_name/token_prefixmake 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 (noBearerprefix) inX-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]) -- AnASGIConnectioninstance.- Raises:
NotAuthorizedException | PermissionDeniedException -- if authentication fails.
- Return type:
- 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_uriis omitted, the validator auto-discovers it from{issuer}/.well-known/openid-configuration. The JWKS document is cached in-memory with the given TTL.- Parameters:
jwks_uri¶ (
Optional[str]) -- Optional explicit JWKS endpoint (overrides discovery).clock_skew¶ (
int) -- Tolerance in seconds forexp/iat/nbfchecks.jwks_cache_ttl¶ (
int) -- JWKS / discovery document TTL in seconds.jwks_cache¶ (
Optional[JWKSCache]) -- Optional sharedJWKSCacheinstance. WhenNonethe process-wide default cache is used.on_validation_error¶ (
Optional[Callable[[str,BaseException], None | Awaitable[None]]]) -- Observability hook invoked on failure.
- Return type:
- Returns:
An async callable suitable for
MCPAuthBackend'stoken_validatorconstructor 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¶
JWKSCache¶
- class litestar_mcp.auth.JWKSCache[source]¶
Bases:
ProtocolShared JWKS / OIDC discovery document cache contract.
getreturns the cached document (fresh, within TTL) orNone.setstamps an expiry at insertion time usingttlseconds.invalidatedrops a single entry; implementations may treatinvalidateas a no-op for unknown URLs.- __init__(*args, **kwargs)¶
DefaultJWKSCache¶
- class litestar_mcp.auth.DefaultJWKSCache[source]¶
Bases:
objectIn-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.