Litestar API#
Litestar integration for py oidc auth.
Litestar is an async framework with dependency injection.
This adapter integrates authentication using Litestar’s litestar.di.Provide.
Install:
pip install py-oidc-auth[litestar]
conda install -c conda-forge py-oidc-auth-litestar
Usage
from litestar import Litestar, get
from py_oidc_auth.litestar_auth import LitestarOIDCAuth
from py_oidc_auth.schema import IDToken
auth = LitestarOIDCAuth(
client_id="my client",
discovery_url="https://idp.example.org/realms/demo/.well-known/openid-configuration",
scopes="myscope profile email",
)
@get("/protected", dependencies={"token": auth.required()})
async def protected(token: IDToken) -> dict:
return {"sub": token.sub}
app = Litestar(route_handlers=[auth.create_auth_router(prefix="/api"), protected])
- class py_oidc_auth.litestar_auth.LitestarOIDCAuth(client_id: str = '', discovery_url: str = '', client_secret: str | None = None, scopes: str = 'profile email', proxy: str = '', claims: Dict[str, Any] | None = None, offline_access: bool = True, timeout_sec: int = 10)#
Reusable OpenID Connect helper for Litestar.
The public surface is:
required()andoptional()for dependency injectioncreate_auth_router()for standard auth routes
- required(claims: Dict[str, Any] | None = None, scopes: str = '') litestar.di.Provide#
Return a
litestar.di.Providethat enforces authentication.- Parameters:
claims – Optional claim constraints.
scopes – Space separated scope names.
- Returns:
Provide instance usable in
dependencies.
Example
@get("/protected", dependencies={"token": auth.required(scopes="admin")}) async def protected(token: IDToken) -> dict: return {"sub": token.sub}
- optional(claims: Dict[str, Any] | None = None, scopes: str = '') litestar.di.Provide#
Return a
litestar.di.Providethat allows anonymous access.- Parameters:
claims – Optional claim constraints.
scopes – Space separated scope names.
- Returns:
Provide instance.
- create_auth_router(prefix: str = '', login: str = '/auth/v2/login', callback: str = '/auth/v2/callback', token: str = '/auth/v2/token', device_flow: str | None = '/auth/v2/device', logout: str | None = '/auth/v2/logout', userinfo: str | None = '/auth/v2/userinfo') litestar.Router#
Build a Litestar
litestar.Routerwith standard auth routes.- Parameters:
prefix – URL prefix for all routes.
login – Path for login.
callback – Path for callback.
token – Path for token exchange and refresh.
device_flow – Path for starting the device flow.
logout – Path for logout.
userinfo – Path for userinfo.
- Returns:
Router instance.
Request example#
GET /auth/v2/userinfo HTTP/1.1 Host: app.example.org Authorization: Bearer <access token>