API Reference¶
This page documents the package public API and optional integration modules.
Core Public API¶
Available in the base install:
AuthConfig(issuer: str, audience: str | Sequence[str], jwks_url: str, allowed_algs: Sequence[str] = ('RS256',), leeway_s: int = 0, jwks_timeout_s: float = 3.0, jwks_cache_ttl_s: float = 300.0, jwks_max_cached_keys: int = 16, enforce_minimum_key_length: bool = True, required_scopes: Sequence[str] = (), required_permissions: Sequence[str] = (), scope_claim: str = 'scope', permissions_claim: str = 'permissions')
dataclass
¶
Immutable configuration for JWT verification.
This dataclass holds all settings required by JWTVerifier to validate
JWTs against an OIDC provider. The configuration is frozen (immutable)
and uses slots for memory efficiency.
All string inputs are stripped of leading/trailing whitespace during validation. Sequences are normalized to tuples.
Attributes:
| Name | Type | Description |
|---|---|---|
issuer |
str
|
The expected |
audience |
str | Sequence[str]
|
One or more expected |
jwks_url |
str
|
The URL to fetch the JSON Web Key Set from. This URL is used for all key lookups; the verifier never derives JWKS URLs from token headers. |
allowed_algs |
Sequence[str]
|
Permitted signing algorithms. Defaults to |
leeway_s |
int
|
Clock skew tolerance in seconds for |
jwks_timeout_s |
float
|
HTTP timeout in seconds for JWKS fetches. Supports fractional seconds. Defaults to 3.0. |
jwks_cache_ttl_s |
float
|
Time-to-live in seconds for cached JWKS data. Supports fractional seconds and must be in the range (0, 86400]. Defaults to 300.0. |
jwks_max_cached_keys |
int
|
Maximum number of signing keys to cache. Must be in the range (0, 1024]. Defaults to 16. |
enforce_minimum_key_length |
bool
|
Whether to reject JWTs signed with
cryptographic keys below PyJWT minimum recommendations.
Defaults to |
required_scopes |
Sequence[str]
|
Scopes that must be present in the token for
authorization to succeed. Checked against the |
required_permissions |
Sequence[str]
|
Permissions that must be present in the token.
Checked against the |
scope_claim |
str
|
The claim name containing OAuth 2.0 scopes. Defaults
to |
permissions_claim |
str
|
The claim name containing permissions (commonly
used by Auth0). Defaults to |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any validation constraint is violated during
construction. Specific conditions include:
- Empty or whitespace-only |
Examples:
Minimal configuration for Auth0:
>>> config = AuthConfig(
... issuer="https://example.auth0.com/",
... audience="https://api.example.com",
... jwks_url="https://example.auth0.com/.well-known/jwks.json",
... )
>>> config.audiences
('https://api.example.com',)
>>> config.allowed_algorithms
('RS256',)
Configuration with multiple audiences and scope requirements:
>>> config = AuthConfig(
... issuer="https://example.auth0.com/",
... audience=[
... "https://api.example.com",
... "https://api2.example.com",
... ],
... jwks_url="https://example.auth0.com/.well-known/jwks.json",
... allowed_algs=["RS256", "RS384"],
... required_scopes=["read:users", "write:users"],
... )
>>> config.audiences
('https://api.example.com', 'https://api2.example.com')
>>> config.required_scope_set
{'read:users', 'write:users'}
Invalid configuration raises ValueError:
>>> AuthConfig(
... issuer="",
... audience="api",
... jwks_url="https://example.com/.well-known/jwks.json",
... )
Traceback (most recent call last):
...
ValueError: issuer must be non-empty
audiences: tuple[str, ...]
property
¶
Return the configured audiences as a tuple.
This property provides consistent tuple access regardless of whether
the audience attribute was initialized with a single string or
a sequence.
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
A tuple of audience strings. |
Examples:
allowed_algorithms: tuple[str, ...]
property
¶
Return the allowed algorithms as a tuple.
This property provides consistent tuple access regardless of whether
the allowed_algs attribute was initialized with a single string
or a sequence.
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
A tuple of algorithm name strings. |
Examples:
required_scope_set: set[str]
property
¶
Return the required scopes as a set for efficient membership testing.
Empty strings in the required_scopes sequence are filtered out.
Returns:
| Type | Description |
|---|---|
set[str]
|
A set of non-empty scope strings. |
Examples:
required_permission_set: set[str]
property
¶
Return the required permissions as a set for efficient membership testing.
Empty strings in the required_permissions sequence are filtered out.
Returns:
| Type | Description |
|---|---|
set[str]
|
A set of non-empty permission strings. |
Examples:
__post_init__() -> None
¶
Validate and normalize configuration values after initialization.
This method runs automatically after dataclass initialization. It strips whitespace from string values, normalizes sequences to tuples, and validates all constraints.
Raises:
| Type | Description |
|---|---|
ValueError
|
If any validation constraint is violated. |
Source code in oidc_jwt_verifier/config.py
AuthError(*, code: str, message: str, status_code: int, required_scopes: Iterable[str] = (), required_permissions: Iterable[str] = ())
¶
Bases: Exception
Exception raised on authentication or authorization failure.
This exception provides structured error information including a stable error code for programmatic handling, an HTTP status code (401 for authentication failures, 403 for authorization failures), and a method to generate RFC 6750-compliant WWW-Authenticate header values.
The exception message is accessible via the standard str() conversion
or the message attribute.
Attributes:
| Name | Type | Description |
|---|---|---|
code |
A stable string identifier for the error type. Common values
include |
|
message |
A human-readable description of the error. This is also set as the exception message. |
|
status_code |
The HTTP status code to return. Must be 401 (Unauthorized) for authentication errors or 403 (Forbidden) for authorization errors. |
|
required_scopes |
A tuple of scope strings that were required but
missing from the token. Populated for |
|
required_permissions |
A tuple of permission strings that were required
but missing from the token. Populated for |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
Creating an authentication error (401):
>>> error = AuthError(
... code="token_expired",
... message="Token is expired",
... status_code=401,
... )
>>> str(error)
'Token is expired'
>>> error.code
'token_expired'
>>> error.status_code
401
Creating an authorization error (403) with scope requirements:
>>> error = AuthError(
... code="insufficient_scope",
... message="Insufficient scope",
... status_code=403,
... required_scopes=["read:users", "write:users"],
... )
>>> error.required_scopes
('read:users', 'write:users')
Generating a WWW-Authenticate header:
>>> error = AuthError(
... code="invalid_token",
... message="Malformed token",
... status_code=401,
... )
>>> error.www_authenticate_header(realm="api")
'Bearer realm="api", error="invalid_token", error_description="Malformed token"'
Invalid status code raises ValueError:
>>> AuthError(code="error", message="msg", status_code=500)
Traceback (most recent call last):
...
ValueError: status_code must be 401 or 403
Initialize an authentication or authorization error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
A stable string identifier for the error type. |
required |
message
|
str
|
A human-readable error description. |
required |
status_code
|
int
|
The HTTP status code (must be 401 or 403). |
required |
required_scopes
|
Iterable[str]
|
Scopes that were required but missing. Defaults to an empty tuple. |
()
|
required_permissions
|
Iterable[str]
|
Permissions that were required but missing. Defaults to an empty tuple. |
()
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in oidc_jwt_verifier/errors.py
www_authenticate_header(*, realm: str | None = None) -> str
¶
Generate an RFC 6750-compliant WWW-Authenticate header value.
Constructs a Bearer authentication challenge suitable for use as the value of an HTTP WWW-Authenticate header. The challenge includes the error type (mapped to RFC 6750 error codes) and a description.
RFC 6750 defines two relevant error codes:
- invalid_token: Used for 401 errors (authentication failures).
- insufficient_scope: Used for 403 errors (authorization failures).
If required_scopes is non-empty, a scope parameter is
included listing the missing scopes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
realm
|
str | None
|
Optional protection space identifier. If provided, it appears first in the challenge parameters. Common values include the API name or domain. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
A string suitable for use as the WWW-Authenticate header value. |
str
|
The format is |
Examples:
Basic authentication error:
>>> error = AuthError(
... code="invalid_token",
... message="Token is expired",
... status_code=401,
... )
>>> error.www_authenticate_header()
'Bearer error="invalid_token", error_description="Token is expired"'
With realm:
>>> error.www_authenticate_header(realm="my-api")
'Bearer realm="my-api", error="invalid_token", error_description="Token is expired"'
Authorization error with required scopes:
>>> error = AuthError(
... code="insufficient_scope",
... message="Insufficient scope",
... status_code=403,
... required_scopes=["read:users"],
... )
>>> header = error.www_authenticate_header()
>>> "insufficient_scope" in header
True
>>> "read:users" in header
True
Source code in oidc_jwt_verifier/errors.py
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 | |
JWTVerifier(config: AuthConfig)
¶
Stateful JWT verifier for OIDC access tokens.
This class performs complete JWT verification including:
- Header validation: Rejects tokens with dangerous headers
(
jku,x5u,crit) and ensures the algorithm is in the allowlist. - Key retrieval: Fetches the signing key from the JWKS using the
token's
kidheader. - Signature verification: Validates the cryptographic signature.
- Claim validation: Checks
iss,aud,exp, andnbfclaims against configuration. - Authorization enforcement: Verifies required scopes and permissions are present (returns 403 on failure).
The verifier maintains a cached JWKS client for efficient key lookups across multiple token verifications.
Attributes:
| Name | Type | Description |
|---|---|---|
_config |
The authentication configuration. |
|
_jwks |
The JWKS client for signing key retrieval. |
|
_decoder |
A configured |
Examples:
Basic token verification:
>>> from oidc_jwt_verifier import AuthConfig, AuthError, JWTVerifier
>>> config = AuthConfig(
... issuer="https://example.auth0.com/",
... audience="https://api.example.com",
... jwks_url="https://example.auth0.com/.well-known/jwks.json",
... )
>>> verifier = JWTVerifier(config)
>>> claims = verifier.verify_access_token(token)
>>> claims["sub"]
'auth0|123456789'
Handling verification errors:
>>> try:
... claims = verifier.verify_access_token(expired_token)
... except AuthError as e:
... print(f"Error: {e.code}, Status: {e.status_code}")
... print(e.www_authenticate_header())
Error: token_expired, Status: 401
Bearer error="invalid_token", error_description="Token is expired"
Verifying tokens with scope requirements:
>>> config = AuthConfig(
... issuer="https://example.auth0.com/",
... audience="https://api.example.com",
... jwks_url="https://example.auth0.com/.well-known/jwks.json",
... required_scopes=["read:users"],
... )
>>> verifier = JWTVerifier(config)
>>> # Token without required scopes raises AuthError with 403
>>> claims = verifier.verify_access_token(
... token_without_scopes
... )
Traceback (most recent call last):
...
AuthError: Insufficient scope
Initialize a JWT verifier with the given configuration.
Creates a JWKS client configured with the caching parameters from the provided configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
AuthConfig
|
The authentication configuration specifying the issuer, audience, JWKS URL, allowed algorithms, and authorization requirements. |
required |
Examples:
>>> from oidc_jwt_verifier import AuthConfig
>>> config = AuthConfig(
... issuer="https://example.auth0.com/",
... audience="https://api.example.com",
... jwks_url="https://example.auth0.com/.well-known/jwks.json",
... )
>>> verifier = JWTVerifier(config)
Source code in oidc_jwt_verifier/verifier.py
verify_access_token(token: str) -> dict[str, Any]
¶
Verify an access token and return its claims.
Performs the complete verification chain:
- Validates the token is non-empty.
- Parses and validates the token header (rejects
jku,x5u,crit; validatesalgandkid). - Fetches the signing key from the JWKS.
- Decodes and verifies the token signature.
- Validates standard claims (
iss,aud,exp,nbf). - Enforces required scopes and permissions.
The method supports Auth0-style multi-audience tokens where the
aud claim is an array. Verification succeeds if any configured
audience matches any audience in the token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The encoded JWT access token string. Leading and trailing whitespace is stripped. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The decoded token payload as a dictionary. Contains all |
dict[str, Any]
|
claims from the token including registered claims ( |
dict[str, Any]
|
|
Raises:
| Type | Description |
|---|---|
AuthError
|
On any verification failure. The error's
Specific error codes include:
- |
Examples:
Successful verification:
>>> claims = verifier.verify_access_token(
... valid_token
... )
>>> claims["sub"]
'auth0|123456789'
>>> claims["aud"]
'https://api.example.com'
Missing token:
>>> verifier.verify_access_token("")
Traceback (most recent call last):
...
AuthError: Missing access token
Expired token:
>>> verifier.verify_access_token(expired_token)
Traceback (most recent call last):
...
AuthError: Token is expired
Source code in oidc_jwt_verifier/verifier.py
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 | |
Optional Async API¶
Requires pip install "oidc-jwt-verifier[async]".
oidc_jwt_verifier.async_jwks.AsyncJWKSClientoidc_jwt_verifier.async_verifier.AsyncJWTVerifier
AsyncJWKSClient(_config: AuthConfig, _client: httpx.AsyncClient, _owns_client: bool, _max_fetch_attempts: int = 2, _jwk_set_cache: PyJWKSet | None = None, _jwk_set_expiry_monotonic: float = 0.0, _key_cache: OrderedDict[str, PyJWK] = OrderedDict(), _lock: asyncio.Lock = asyncio.Lock())
dataclass
¶
Asynchronous JWKS client with TTL and key caching.
The client supports:
- Async JWKS fetches via
httpx.AsyncClient. - JWKS document caching with
jwks_cache_ttl_s. - Key-object caching with
jwks_max_cached_keys. - Error mapping to stable
AuthErrorcodes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
_config
|
AuthConfig
|
Auth configuration. |
required |
_client
|
AsyncClient
|
Async HTTP client used for JWKS fetches. |
required |
_owns_client
|
bool
|
Whether this instance must close |
required |
_max_fetch_attempts
|
int
|
Number of total fetch attempts for transient
request failures. Minimum value is |
2
|
_jwk_set_cache
|
PyJWKSet | None
|
Cached parsed JWKS set. |
None
|
_jwk_set_expiry_monotonic
|
float
|
Monotonic timestamp when JWKS cache expires. |
0.0
|
_key_cache
|
OrderedDict[str, PyJWK]
|
LRU-like cache of |
OrderedDict()
|
_lock
|
Lock
|
Async lock protecting cache state. |
Lock()
|
Examples:
>>> from oidc_jwt_verifier import AuthConfig
>>> from oidc_jwt_verifier.async_jwks import AsyncJWKSClient
>>> config = AuthConfig(
... issuer="https://issuer.example/",
... audience="https://api.example",
... jwks_url="https://issuer.example/.well-known/jwks.json",
... )
>>> client = AsyncJWKSClient.from_config(config)
>>> # await client.get_signing_key_from_jwt(token)
>>> # await client.aclose()
from_config(config: AuthConfig, *, http_client: httpx.AsyncClient | None = None, max_fetch_attempts: int = 2) -> AsyncJWKSClient
classmethod
¶
Create an async JWKS client from configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
AuthConfig
|
Auth configuration with JWKS URL/cache/timeout settings. |
required |
http_client
|
AsyncClient | None
|
Optional externally managed client. If omitted, an internal client is created and owned by this instance. |
None
|
max_fetch_attempts
|
int
|
Total fetch attempts for request failures.
Must be |
2
|
Returns:
| Type | Description |
|---|---|
AsyncJWKSClient
|
Configured |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> from oidc_jwt_verifier import AuthConfig
>>> config = AuthConfig(
... issuer="https://issuer.example/",
... audience="https://api.example",
... jwks_url="https://issuer.example/.well-known/jwks.json",
... )
>>> client = AsyncJWKSClient.from_config(config)
Source code in oidc_jwt_verifier/async_jwks.py
aclose() -> None
async
¶
Close internal resources.
Closes the underlying HTTP client only when this instance owns it.
Examples:
Source code in oidc_jwt_verifier/async_jwks.py
get_signing_key_from_jwt(token: str | bytes) -> PyJWK
async
¶
Resolve signing key for a JWT from configured JWKS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str | bytes
|
Encoded JWT as |
required |
Returns:
| Type | Description |
|---|---|
PyJWK
|
Matching signing key. |
Raises:
| Type | Description |
|---|---|
AuthError
|
On key lookup/fetch/parsing failures. |
Examples:
Source code in oidc_jwt_verifier/async_jwks.py
get_signing_key(kid: str) -> PyJWK
async
¶
Resolve a signing key by kid.
Performs lookup against cache first, then fetches/retries JWKS when
needed, including one forced refresh attempt when kid is missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kid
|
str
|
JWT key identifier. |
required |
Returns:
| Type | Description |
|---|---|
PyJWK
|
Matching |
Raises:
| Type | Description |
|---|---|
AuthError
|
With |
Examples:
Source code in oidc_jwt_verifier/async_jwks.py
AsyncJWTVerifier(config: AuthConfig, *, jwks_client: AsyncJWKSClient | None = None, http_client: httpx.AsyncClient | None = None)
¶
Stateful asynchronous JWT verifier for OIDC access tokens.
This verifier preserves sync-path semantics while using asynchronous JWKS fetches and key lookups.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
AuthConfig
|
Authentication configuration. |
required |
jwks_client
|
AsyncJWKSClient | None
|
Optional externally managed async JWKS client. |
None
|
http_client
|
AsyncClient | None
|
Optional externally managed |
None
|
Examples:
>>> from oidc_jwt_verifier import AuthConfig
>>> from oidc_jwt_verifier.async_verifier import AsyncJWTVerifier
>>> config = AuthConfig(
... issuer="https://example.auth0.com/",
... audience="https://api.example.com",
... jwks_url="https://example.auth0.com/.well-known/jwks.json",
... )
>>> verifier = AsyncJWTVerifier(config)
Initialize an async verifier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
AuthConfig
|
Authentication configuration. |
required |
jwks_client
|
AsyncJWKSClient | None
|
Optional injected async JWKS client. |
None
|
http_client
|
AsyncClient | None
|
Optional injected HTTP client for internally created async JWKS client. |
None
|
Source code in oidc_jwt_verifier/async_verifier.py
verify_access_token(token: str) -> dict[str, Any]
async
¶
Verify a JWT access token and return its claims.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
Encoded JWT string. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Decoded JWT payload. |
Raises:
| Type | Description |
|---|---|
AuthError
|
On authentication or authorization failure. |
Source code in oidc_jwt_verifier/async_verifier.py
aclose() -> None
async
¶
Close verifier-owned async resources.
If the verifier created its own async JWKS client, this method closes that client and its owned HTTP resources.
Source code in oidc_jwt_verifier/async_verifier.py
__aenter__() -> AsyncJWTVerifier
async
¶
Enter async context manager for the verifier.
Returns:
| Type | Description |
|---|---|
AsyncJWTVerifier
|
This verifier instance. |
__aexit__(_exc_type: object, _exc: object, _tb: object) -> None
async
¶
Optional FastAPI Integration API¶
Requires pip install "oidc-jwt-verifier[fastapi]".
oidc_jwt_verifier.integrations.fastapi.auth_error_to_http_exceptionoidc_jwt_verifier.integrations.fastapi.create_async_bearer_dependencyoidc_jwt_verifier.integrations.fastapi.create_sync_bearer_dependency
fastapi
¶
FastAPI integration helpers.
This module provides dependency factories that translate AuthError into
fastapi.HTTPException while preserving RFC 6750 WWW-Authenticate
headers.
auth_error_to_http_exception(error: AuthError, *, realm: str | None = None) -> HTTPException
¶
Translate AuthError into fastapi.HTTPException.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
AuthError
|
Auth error to convert. |
required |
realm
|
str | None
|
Optional RFC 6750 realm parameter. |
None
|
Returns:
| Type | Description |
|---|---|
HTTPException
|
A FastAPI HTTP exception with status, detail and |
HTTPException
|
|
Source code in oidc_jwt_verifier/integrations/fastapi.py
create_async_bearer_dependency(verifier: AsyncJWTVerifier, *, realm: str | None = None, auto_error: bool = False) -> Callable[[HTTPAuthorizationCredentials | None], Awaitable[dict[str, Any]]]
¶
Create a FastAPI dependency for AsyncJWTVerifier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verifier
|
AsyncJWTVerifier
|
Async verifier instance. |
required |
realm
|
str | None
|
Optional RFC 6750 realm. |
None
|
auto_error
|
bool
|
Passed to |
False
|
Returns:
| Type | Description |
|---|---|
Callable[[HTTPAuthorizationCredentials | None], Awaitable[dict[str, Any]]]
|
A dependency callable returning decoded claims on success. |
Source code in oidc_jwt_verifier/integrations/fastapi.py
create_sync_bearer_dependency(verifier: JWTVerifier, *, realm: str | None = None, offload_to_threadpool: bool = True, auto_error: bool = False) -> Callable[[HTTPAuthorizationCredentials | None], Awaitable[dict[str, Any]]]
¶
Create a FastAPI dependency for sync JWTVerifier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verifier
|
JWTVerifier
|
Sync verifier instance. |
required |
realm
|
str | None
|
Optional RFC 6750 realm. |
None
|
offload_to_threadpool
|
bool
|
Whether to run sync verification in
|
True
|
auto_error
|
bool
|
Passed to |
False
|
Returns:
| Type | Description |
|---|---|
Callable[[HTTPAuthorizationCredentials | None], Awaitable[dict[str, Any]]]
|
A dependency callable returning decoded claims on success. |
Source code in oidc_jwt_verifier/integrations/fastapi.py
Optional Starlette Integration API¶
Requires pip install "oidc-jwt-verifier[starlette]".
oidc_jwt_verifier.integrations.starlette.BearerAuthMiddlewareoidc_jwt_verifier.integrations.starlette.verify_request_bearer_tokenoidc_jwt_verifier.integrations.starlette.auth_error_to_response
starlette
¶
Starlette integration helpers.
This module offers middleware and helper functions to apply verifier logic in Starlette applications while preserving RFC 6750 response semantics.
Returns:
| Type | Description |
|---|---|
|
None. |
Examples:
BearerAuthMiddleware(app: ASGIApp, *, verifier: JWTVerifier | AsyncJWTVerifier, realm: str | None = None, exempt_paths: set[str] | None = None, claims_state_key: str = 'auth_claims')
¶
Starlette middleware that verifies bearer access tokens.
Valid claims are stored in request.state under claims_state_key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
ASGIApp
|
Downstream ASGI app. |
required |
verifier
|
JWTVerifier | AsyncJWTVerifier
|
Sync or async verifier. |
required |
realm
|
str | None
|
Optional realm for RFC 6750 header generation. |
None
|
exempt_paths
|
set[str] | None
|
Paths to skip authentication for. |
None
|
claims_state_key
|
str
|
Key used in |
'auth_claims'
|
Returns:
| Type | Description |
|---|---|
|
None. |
Examples:
>>> from starlette.applications import Starlette
>>> app = Starlette()
>>> _ = BearerAuthMiddleware(app, verifier=verifier)
Initialize middleware configuration.
Source code in oidc_jwt_verifier/integrations/starlette.py
__call__(scope: Scope, receive: Receive, send: Send) -> None
async
¶
Process request authentication.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scope
|
Scope
|
ASGI scope. |
required |
receive
|
Receive
|
ASGI receive callable. |
required |
send
|
Send
|
ASGI send callable. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None. |
Examples:
>>> # Invoked by Starlette's ASGI runtime, not called directly.
>>> # await middleware(scope, receive, send)
Source code in oidc_jwt_verifier/integrations/starlette.py
auth_error_to_response(error: AuthError, *, realm: str | None = None) -> JSONResponse
¶
Convert AuthError into a Starlette JSON response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
error
|
AuthError
|
Auth error to convert. |
required |
realm
|
str | None
|
Optional realm for |
None
|
Returns:
| Type | Description |
|---|---|
JSONResponse
|
JSON response with correct status and RFC 6750 header. |
Examples:
>>> from oidc_jwt_verifier.errors import AuthError
>>> error = AuthError(code="invalid_token", message="bad token")
>>> response = auth_error_to_response(error)
>>> response.status_code
401
Source code in oidc_jwt_verifier/integrations/starlette.py
extract_bearer_token(authorization_header: str | None) -> str
¶
Extract a bearer token from Authorization header value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
authorization_header
|
str | None
|
Raw header value. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Bearer token string, or empty string when missing/invalid. |
Examples:
>>> extract_bearer_token("Bearer abc.def.ghi")
'abc.def.ghi'
>>> extract_bearer_token("Basic abc")
''
Source code in oidc_jwt_verifier/integrations/starlette.py
verify_request_bearer_token(request: Request, *, verifier: JWTVerifier | AsyncJWTVerifier) -> dict[str, Any]
async
¶
Verify bearer token from a Starlette request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Incoming request. |
required |
verifier
|
JWTVerifier | AsyncJWTVerifier
|
Sync or async verifier instance. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Decoded JWT claims. |
Raises:
| Type | Description |
|---|---|
AuthError
|
On authentication/authorization failure. |
Examples:
>>> # Usually called from middleware with a Starlette ``Request``.
>>> # claims = await verify_request_bearer_token(request, verifier=verifier)