API reference¶
Everything below fastapi_multiauth is importable from the package root:
from fastapi_multiauth import (
APIKeyCookieAuth,
APIKeyHeaderAuth,
APIKeyQueryAuth,
AuthSource,
AuthenticationMethodReference,
ForbiddenError,
HMACSignatureAuth,
HTTPBasicAuth,
HTTPBearerAuth,
HTTPDPoPAuth, # needs the jwt extra at construction
InsufficientAuthenticationError,
IntrospectionValidator,
JWTValidator, # needs the jwt extra at construction
MultiAuth,
OAuth2AuthorizationCodeBearerAuth,
OAuth2PasswordBearerAuth,
OpenIdConnectAuth,
RouteAuth,
SchemeRequirement,
StaleCredentialError,
UnauthorizedError,
auth_surface,
checksum_token_generator,
hash_token,
totp_generate_secret,
totp_provisioning_uri,
totp_verify,
verify_token_checksum,
verify_token_hash,
)
The OAuth login helpers live in fastapi_multiauth.oauth and need the oauth extra:
from fastapi_multiauth.oauth import (
OAuthDiscoveryError,
OAuthError,
OAuthExchangeError,
OAuthIDTokenError,
OAuthStateError,
OAuthUserinfoError,
OIDCEndpoints,
oauth_build_authorization_redirect,
oauth_decode_state,
oauth_encode_state,
oauth_exchange_code,
oauth_fetch_userinfo,
oauth_generate_nonce,
oauth_generate_pkce_pair,
oauth_generate_state_token,
oauth_resolve_provider_urls,
oauth_validate_id_token,
)
Sources¶
Request-time authentication dependencies. Guide: the sources.
fastapi_multiauth.AuthSource ¶
AuthSource(scheme: Any = None)
Bases: ABC
Base class for authentication sources.
Subclass it to read a credential the built-in sources do not handle. Implement extract() and authenticate(); override www_authenticate(), authenticated_at(), authenticated_acr() or authenticate_scoped() when the source needs them, and set authorization_scheme on a source that reads the Authorization header.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scheme | Any | A | None |
- Guide Sources Custom sources
authorization_scheme class-attribute instance-attribute ¶
authorization_scheme: str | None = None
The Authorization scheme this source reads, lowercased: "*" for any scheme, None when it does not read the header. Under MultiAuth, a header of a scheme a source reads, which no such source takes, is refused instead of passing to a cookie or an API key.
extract abstractmethod async ¶
extract(request: HTTPConnection) -> str | None
Return the credential found in the request, without validating it.
Return None, never an empty string, when the credential is absent, empty, or belongs to another source: this is what lets MultiAuth try the next source and optional() serve an anonymous caller.
authenticate abstractmethod async ¶
Validate a credential and return the identity, or raise to refuse it.
www_authenticate ¶
www_authenticate() -> str | None
Return the WWW-Authenticate challenge sent with this source's 401s.
Returns:
| Type | Description |
|---|---|
str | None | The challenge, or |
authenticate_scoped async ¶
authenticate_scoped(
credential: str,
scopes: list[str],
*,
request: HTTPConnection | None = None,
) -> Any
Validate a credential against the scopes the route declares.
The default refuses any route that declares scopes, since authenticate() cannot check them. Override it to enforce scopes or to use the request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
scopes | list[str] | The scopes declared on the route, empty when there are none. | required |
request | HTTPConnection | None | The request or WebSocket being authenticated, | None |
optional ¶
optional() -> Self
Return a copy that yields None instead of a 401 when no credential is sent.
A credential that is sent and refused still gets its 401 or 403.
Raises:
| Type | Description |
|---|---|
ValueError | On a copy made by |
authenticated_at ¶
Return when a credential was proven, for fresh().
Override it in a source that can date its own credentials, as the signed cookie does. It runs on every authenticated request, whether or not the route asks for freshness, since ensure_fresh() may ask later: return None rather than raise for a credential it cannot date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | Epoch seconds or a |
fresh ¶
fresh(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Self
Return a copy that refuses a credential proven more than max_age ago.
The refusal is a 401 with the RFC 9470 max_age challenge. Composes with stepped_up() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | Sync or async callable taking the identity and returning when it was proven, as epoch seconds or a | None |
leeway | float | Clock-skew tolerance in seconds. It applies both ways: an instant further than | 0.0 |
Raises:
| Type | Description |
|---|---|
ValueError | If |
authenticated ¶
authenticated(request: HTTPConnection) -> bool
Whether this source, or a copy of it, authenticated request.
Lets a route served by several sources tell which one was used, e.g. to check freshness only for a cookie session.
ensure_fresh async ¶
ensure_fresh(
request: HTTPConnection,
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> None
Refuse request if this source authenticated it more than max_age ago.
The fresh() check, for a handler that only knows once the body is parsed whether it needs a recent login. It reads what this source recorded when it authenticated the request: the validator never runs again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request this source authenticated. | required |
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | As in | None |
leeway | float | As in | 0.0 |
Raises:
| Type | Description |
|---|---|
StaleCredentialError | If the credential is too old or cannot be dated, with the same |
UnauthorizedError | If the request carries no credential for this source. |
RuntimeError | If it carries one this source did not authenticate. |
ValueError | As |
fresh_guard ¶
fresh_guard(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Callable[[HTTPConnection], Awaitable[None]]
Return a dependency running ensure_fresh(), for a whole route.
Unlike fresh(), it adds a check after the route's own auth dependency instead of replacing it, so the validator runs once. It must come after that dependency: a parameter after it, or later in the same dependencies=[...] list.
Raises:
| Type | Description |
|---|---|
ValueError | As |
authenticated_acr ¶
Return the acr a credential was proven at, for stepped_up().
Override it in a source that carries the level in its own credentials, as the signed cookie does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | The level, |
stepped_up ¶
Return a copy that refuses a credential not proven at one of acr_values.
The refusal is a 401 with the RFC 9470 acr_values challenge. Composes with fresh() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
acr_values | Sequence[str] | The accepted authentication context class references; any one of them passes. | required |
acr | Callable[..., Any] | None | Sync or async callable taking the identity and returning the | None |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
dispatch async ¶
dispatch(request: HTTPConnection, scopes: list[str]) -> Any
Authenticate a request: extract the credential, then validate it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request or WebSocket being authenticated. | required |
scopes | list[str] | The scopes declared on the route. | required |
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If no credential is present. Every 401 carries this source's |
RuntimeError | If an |
fastapi_multiauth.HTTPBearerAuth ¶
HTTPBearerAuth(
validator: Callable[..., Any],
*,
prefix: str | None = None,
allow_dpop_bound: bool = False,
scheme_name: str | None = None,
description: str | None = None,
bearer_format: str | None = None,
token_generator: Callable[[int], str] = token_urlsafe,
**kwargs: Any,
)
Bases: _BearerSource
Authentication source for Authorization: Bearer tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validator | Callable[..., Any] | Sync or async callable returning the identity, or raising to refuse. | required |
prefix | str | None | Only accept tokens starting with this, e.g. | None |
allow_dpop_bound | bool | Accept a DPoP-bound token ( | False |
scheme_name | str | None | Name of the security scheme in OpenAPI, | None |
description | str | None | Description of the security scheme in OpenAPI. | None |
bearer_format | str | None | Format hint shown in OpenAPI, e.g. | None |
token_generator | Callable[[int], str] | Callable building a token body from | token_urlsafe |
**kwargs | Any | Keyword arguments passed to the validator on every call. | {} |
- Guide
- Sources Bearer tokens
- The sources
extract async ¶
extract(request: HTTPConnection) -> str | None
Return the bearer token, or None when absent, empty, or without the prefix.
The Bearer scheme is matched case-insensitively, and the prefix is kept in the returned token.
authenticate async ¶
authenticate(
credential: str,
*,
request: HTTPConnection | None = None,
) -> Any
Validate a credential and return the identity, ignoring route scopes.
authenticate_scoped async ¶
authenticate_scoped(
credential: str,
scopes: list[str],
*,
request: HTTPConnection | None = None,
) -> Any
Validate the token, passing the route's scopes and request on.
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If the token is DPoP-bound ( |
optional ¶
optional() -> Self
Return a copy that yields None instead of a 401 when no credential is sent.
A credential that is sent and refused still gets its 401 or 403.
Raises:
| Type | Description |
|---|---|
ValueError | On a copy made by |
authenticated_at ¶
Return when a credential was proven, for fresh().
Override it in a source that can date its own credentials, as the signed cookie does. It runs on every authenticated request, whether or not the route asks for freshness, since ensure_fresh() may ask later: return None rather than raise for a credential it cannot date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | Epoch seconds or a |
fresh ¶
fresh(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Self
Return a copy that refuses a credential proven more than max_age ago.
The refusal is a 401 with the RFC 9470 max_age challenge. Composes with stepped_up() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | Sync or async callable taking the identity and returning when it was proven, as epoch seconds or a | None |
leeway | float | Clock-skew tolerance in seconds. It applies both ways: an instant further than | 0.0 |
Raises:
| Type | Description |
|---|---|
ValueError | If |
authenticated ¶
authenticated(request: HTTPConnection) -> bool
Whether this source, or a copy of it, authenticated request.
Lets a route served by several sources tell which one was used, e.g. to check freshness only for a cookie session.
ensure_fresh async ¶
ensure_fresh(
request: HTTPConnection,
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> None
Refuse request if this source authenticated it more than max_age ago.
The fresh() check, for a handler that only knows once the body is parsed whether it needs a recent login. It reads what this source recorded when it authenticated the request: the validator never runs again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request this source authenticated. | required |
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | As in | None |
leeway | float | As in | 0.0 |
Raises:
| Type | Description |
|---|---|
StaleCredentialError | If the credential is too old or cannot be dated, with the same |
UnauthorizedError | If the request carries no credential for this source. |
RuntimeError | If it carries one this source did not authenticate. |
ValueError | As |
fresh_guard ¶
fresh_guard(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Callable[[HTTPConnection], Awaitable[None]]
Return a dependency running ensure_fresh(), for a whole route.
Unlike fresh(), it adds a check after the route's own auth dependency instead of replacing it, so the validator runs once. It must come after that dependency: a parameter after it, or later in the same dependencies=[...] list.
Raises:
| Type | Description |
|---|---|
ValueError | As |
authenticated_acr ¶
Return the acr a credential was proven at, for stepped_up().
Override it in a source that carries the level in its own credentials, as the signed cookie does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | The level, |
stepped_up ¶
Return a copy that refuses a credential not proven at one of acr_values.
The refusal is a 401 with the RFC 9470 acr_values challenge. Composes with fresh() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
acr_values | Sequence[str] | The accepted authentication context class references; any one of them passes. | required |
acr | Callable[..., Any] | None | Sync or async callable taking the identity and returning the | None |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
dispatch async ¶
dispatch(request: HTTPConnection, scopes: list[str]) -> Any
Authenticate a request: extract the credential, then validate it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request or WebSocket being authenticated. | required |
scopes | list[str] | The scopes declared on the route. | required |
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If no credential is present. Every 401 carries this source's |
RuntimeError | If an |
require ¶
Return a copy that passes extra keyword arguments to the validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs | Any | Keyword arguments added to, or overriding, the source's own. | {} |
Raises:
| Type | Description |
|---|---|
ValueError | If a reserved name ( |
generate_token ¶
Generate a new random token, with the source's prefix in front.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nbytes | int | Bytes of entropy, passed to | 32 |
Returns:
| Type | Description |
|---|---|
str | The token, e.g. |
str | never the token itself. |
Raises:
| Type | Description |
|---|---|
ValueError | If the generator returns an empty token, or one with leading or trailing whitespace. |
fastapi_multiauth.HTTPDPoPAuth ¶
HTTPDPoPAuth(
validator: Callable[..., Any],
*,
replay_check: Callable[[str, float], Any]
| NoReplayCheck
| None = None,
algorithms: Sequence[str] = _DEFAULT_ALGORITHMS,
proof_max_age: float = 60.0,
leeway: float = 5.0,
public_origin: str | None = None,
jkt: Callable[..., Any] | None = None,
scheme_name: str | None = None,
description: str | None = None,
**kwargs: Any,
)
Bases: ValidatedAuthSource
Authentication source for DPoP-bound access tokens (RFC 9449).
A stolen bearer token works for anyone; a DPoP-bound one only works with the private key it is bound to. The client sends Authorization: DPoP <token> and a DPoP header: a short JWT, signed with its key, naming the method and URL of this request. The source checks that proof, passes the token to the validator, then checks the token's cnf.jkt claim names the proof's key. Needs the jwt extra.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validator | Callable[..., Any] | Sync or async callable returning the identity, or raising to refuse, e.g. a | required |
replay_check | Callable[[str, float], Any] | NoReplayCheck | None | Sync or async callable taking a proof's | None |
algorithms | Sequence[str] | Accepted proof algorithms; asymmetric only. | _DEFAULT_ALGORITHMS |
proof_max_age | float | How old a proof may be, in seconds. | 60.0 |
leeway | float | Clock-skew tolerance in seconds for the proof's | 5.0 |
public_origin | str | None | The scheme and host clients call, e.g. | None |
jkt | Callable[..., Any] | None | Sync or async callable taking the identity and returning the thumbprint the token is bound to. Defaults to reading | None |
scheme_name | str | None | Name of the security scheme in OpenAPI, | None |
description | str | None | Description of the security scheme in OpenAPI. | None |
**kwargs | Any | Keyword arguments passed to the validator on every call. | {} |
Raises:
| Type | Description |
|---|---|
ValueError | On an invalid configuration, such as no |
NO_REPLAY_CHECK class-attribute ¶
Explicit replay_check opt-out.
authenticate async ¶
authenticate(
credential: str,
*,
request: HTTPConnection | None = None,
) -> Any
Validate a credential and return the identity, ignoring route scopes.
optional ¶
optional() -> Self
Return a copy that yields None instead of a 401 when no credential is sent.
A credential that is sent and refused still gets its 401 or 403.
Raises:
| Type | Description |
|---|---|
ValueError | On a copy made by |
authenticated_at ¶
Return when a credential was proven, for fresh().
Override it in a source that can date its own credentials, as the signed cookie does. It runs on every authenticated request, whether or not the route asks for freshness, since ensure_fresh() may ask later: return None rather than raise for a credential it cannot date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | Epoch seconds or a |
fresh ¶
fresh(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Self
Return a copy that refuses a credential proven more than max_age ago.
The refusal is a 401 with the RFC 9470 max_age challenge. Composes with stepped_up() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | Sync or async callable taking the identity and returning when it was proven, as epoch seconds or a | None |
leeway | float | Clock-skew tolerance in seconds. It applies both ways: an instant further than | 0.0 |
Raises:
| Type | Description |
|---|---|
ValueError | If |
authenticated ¶
authenticated(request: HTTPConnection) -> bool
Whether this source, or a copy of it, authenticated request.
Lets a route served by several sources tell which one was used, e.g. to check freshness only for a cookie session.
ensure_fresh async ¶
ensure_fresh(
request: HTTPConnection,
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> None
Refuse request if this source authenticated it more than max_age ago.
The fresh() check, for a handler that only knows once the body is parsed whether it needs a recent login. It reads what this source recorded when it authenticated the request: the validator never runs again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request this source authenticated. | required |
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | As in | None |
leeway | float | As in | 0.0 |
Raises:
| Type | Description |
|---|---|
StaleCredentialError | If the credential is too old or cannot be dated, with the same |
UnauthorizedError | If the request carries no credential for this source. |
RuntimeError | If it carries one this source did not authenticate. |
ValueError | As |
fresh_guard ¶
fresh_guard(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Callable[[HTTPConnection], Awaitable[None]]
Return a dependency running ensure_fresh(), for a whole route.
Unlike fresh(), it adds a check after the route's own auth dependency instead of replacing it, so the validator runs once. It must come after that dependency: a parameter after it, or later in the same dependencies=[...] list.
Raises:
| Type | Description |
|---|---|
ValueError | As |
authenticated_acr ¶
Return the acr a credential was proven at, for stepped_up().
Override it in a source that carries the level in its own credentials, as the signed cookie does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | The level, |
stepped_up ¶
Return a copy that refuses a credential not proven at one of acr_values.
The refusal is a 401 with the RFC 9470 acr_values challenge. Composes with fresh() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
acr_values | Sequence[str] | The accepted authentication context class references; any one of them passes. | required |
acr | Callable[..., Any] | None | Sync or async callable taking the identity and returning the | None |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
dispatch async ¶
dispatch(request: HTTPConnection, scopes: list[str]) -> Any
Authenticate a request: extract the credential, then validate it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request or WebSocket being authenticated. | required |
scopes | list[str] | The scopes declared on the route. | required |
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If no credential is present. Every 401 carries this source's |
RuntimeError | If an |
require ¶
Return a copy that passes extra keyword arguments to the validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs | Any | Keyword arguments added to, or overriding, the source's own. | {} |
Raises:
| Type | Description |
|---|---|
ValueError | If a reserved name ( |
www_authenticate ¶
www_authenticate() -> str
Return the DPoP challenge listing the accepted algorithms.
extract async ¶
extract(request: HTTPConnection) -> str | None
Return the token of an Authorization: DPoP header, None when absent.
authenticate_scoped async ¶
authenticate_scoped(
credential: str,
scopes: list[str],
*,
request: HTTPConnection | None = None,
) -> Any
Check the proof, validate the token, then check the token is bound to the proof's key.
A proof's jti is recorded last, so a refused request never uses it up.
Raises:
| Type | Description |
|---|---|
UnauthorizedError | With |
fastapi_multiauth.APIKeyCookieAuth ¶
APIKeyCookieAuth(
name: str,
validator: Callable[..., Any],
*,
secret_key: str | Sequence[str] | None = None,
session_id: bool = False,
csrf: bool = True,
trusted_origins: Sequence[str] = (),
ttl: int = 86400,
secure: bool = True,
samesite: SameSite = "lax",
domain: str | None = None,
path: str = "/",
scheme_name: str | None = None,
description: str | None = None,
**kwargs: Any,
)
Bases: ValidatedAuthSource
Authentication source for cookies, signed into sessions with a secret_key.
With a secret_key, the cookie is signed with HMAC-SHA256, bound to its name, and expires after ttl: a session without a session table. The validator receives the plain value once the signature checks out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Cookie name. Prefer a | required |
validator | Callable[..., Any] | Sync or async callable returning the identity, or raising to refuse. | required |
secret_key | str | Sequence[str] | None | Signing key of at least 32 bytes, or a list to rotate keys (the first signs, all verify). | None |
session_id | bool | Give each session a random id, passed to the validator as | False |
csrf | bool | Refuse cross-origin requests with a 403, judged from the | True |
trusted_origins | Sequence[str] | Other origins the CSRF check lets through, such as | () |
ttl | int | Lifetime in seconds, also checked server-side when signed. | 86400 |
secure | bool | Send the cookie over HTTPS only. Turn off for local HTTP only. | True |
samesite | SameSite | The | 'lax' |
domain | str | None | The | None |
path | str | The | '/' |
scheme_name | str | None | Name of the security scheme in OpenAPI, | None |
description | str | None | Description of the security scheme in OpenAPI. | None |
**kwargs | Any | Keyword arguments passed to the validator on every call. | {} |
Raises:
| Type | Description |
|---|---|
ValueError | On an invalid configuration, such as a short key, a |
- Guide
- Sources Cookie sessions
- The sources
authorization_scheme class-attribute instance-attribute ¶
authorization_scheme: str | None = None
The Authorization scheme this source reads, lowercased: "*" for any scheme, None when it does not read the header. Under MultiAuth, a header of a scheme a source reads, which no such source takes, is refused instead of passing to a cookie or an API key.
authenticate async ¶
authenticate(
credential: str,
*,
request: HTTPConnection | None = None,
) -> Any
Validate a credential and return the identity, ignoring route scopes.
www_authenticate ¶
www_authenticate() -> str | None
Return the WWW-Authenticate challenge sent with this source's 401s.
Returns:
| Type | Description |
|---|---|
str | None | The challenge, or |
optional ¶
optional() -> Self
Return a copy that yields None instead of a 401 when no credential is sent.
A credential that is sent and refused still gets its 401 or 403.
Raises:
| Type | Description |
|---|---|
ValueError | On a copy made by |
fresh ¶
fresh(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Self
Return a copy that refuses a credential proven more than max_age ago.
The refusal is a 401 with the RFC 9470 max_age challenge. Composes with stepped_up() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | Sync or async callable taking the identity and returning when it was proven, as epoch seconds or a | None |
leeway | float | Clock-skew tolerance in seconds. It applies both ways: an instant further than | 0.0 |
Raises:
| Type | Description |
|---|---|
ValueError | If |
authenticated ¶
authenticated(request: HTTPConnection) -> bool
Whether this source, or a copy of it, authenticated request.
Lets a route served by several sources tell which one was used, e.g. to check freshness only for a cookie session.
ensure_fresh async ¶
ensure_fresh(
request: HTTPConnection,
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> None
Refuse request if this source authenticated it more than max_age ago.
The fresh() check, for a handler that only knows once the body is parsed whether it needs a recent login. It reads what this source recorded when it authenticated the request: the validator never runs again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request this source authenticated. | required |
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | As in | None |
leeway | float | As in | 0.0 |
Raises:
| Type | Description |
|---|---|
StaleCredentialError | If the credential is too old or cannot be dated, with the same |
UnauthorizedError | If the request carries no credential for this source. |
RuntimeError | If it carries one this source did not authenticate. |
ValueError | As |
fresh_guard ¶
fresh_guard(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Callable[[HTTPConnection], Awaitable[None]]
Return a dependency running ensure_fresh(), for a whole route.
Unlike fresh(), it adds a check after the route's own auth dependency instead of replacing it, so the validator runs once. It must come after that dependency: a parameter after it, or later in the same dependencies=[...] list.
Raises:
| Type | Description |
|---|---|
ValueError | As |
stepped_up ¶
Return a copy that refuses a credential not proven at one of acr_values.
The refusal is a 401 with the RFC 9470 acr_values challenge. Composes with fresh() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
acr_values | Sequence[str] | The accepted authentication context class references; any one of them passes. | required |
acr | Callable[..., Any] | None | Sync or async callable taking the identity and returning the | None |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
dispatch async ¶
dispatch(request: HTTPConnection, scopes: list[str]) -> Any
Authenticate a request: extract the credential, then validate it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request or WebSocket being authenticated. | required |
scopes | list[str] | The scopes declared on the route. | required |
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If no credential is present. Every 401 carries this source's |
RuntimeError | If an |
require ¶
Return a copy that passes extra keyword arguments to the validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs | Any | Keyword arguments added to, or overriding, the source's own. | {} |
Raises:
| Type | Description |
|---|---|
ValueError | If a reserved name ( |
authenticated_at ¶
Return when the signed cookie was set, None when it does not verify.
authenticated_acr ¶
Return the acr passed to set_cookie(), None when absent or forged.
extract async ¶
extract(request: HTTPConnection) -> str | None
Return the cookie value, or None when absent or empty.
session_id_of ¶
session_id_of(request: HTTPConnection) -> str | None
acr_of ¶
acr_of(request: HTTPConnection) -> str | None
amr_of ¶
amr_of(request: HTTPConnection) -> tuple[str, ...] | None
authenticate_scoped async ¶
authenticate_scoped(
credential: str,
scopes: list[str],
*,
request: HTTPConnection | None = None,
) -> Any
Verify the cookie and its origin, then pass its value on to the validator.
set_cookie ¶
set_cookie(
response: Response,
value: str,
*,
acr: str | None = None,
amr: Sequence[str] | None = None,
) -> str | None
Set the cookie on response, signed when a secret_key is configured.
Each call stamps the current time, so the caller counts as freshly authenticated for fresh().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response | Response | The response to set the cookie on. | required |
value | str | The value to store, typically a user id. | required |
acr | str | None | The level the user just authenticated at, checked by | None |
amr | Sequence[str] | None | The methods the user just authenticated with, e.g. | None |
Returns:
| Type | Description |
|---|---|
str | None | The new session id when |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
delete_cookie ¶
delete_cookie(
response: Response,
request: HTTPConnection | None = None,
) -> str | None
Clear the cookie on response, signing this browser out.
The signed cookie itself stays valid until it expires. With session_id on, revoke the returned id to end the session for real.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response | Response | The response to clear the cookie on. | required |
request | HTTPConnection | None | The current request, to read its session id from. | None |
Returns:
| Type | Description |
|---|---|
str | None | The request's session id when its cookie verifies, otherwise |
fastapi_multiauth.APIKeyHeaderAuth ¶
APIKeyHeaderAuth(
name: str,
validator: Callable[..., Any],
*,
scheme_name: str | None = None,
description: str | None = None,
**kwargs: Any,
)
Bases: ValidatedAuthSource
Authentication source for an API key in a request header.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Header name, e.g. | required |
validator | Callable[..., Any] | Sync or async callable returning the identity, or raising to refuse. | required |
scheme_name | str | None | Name of the security scheme in OpenAPI, | None |
description | str | None | Description of the security scheme in OpenAPI. | None |
**kwargs | Any | Keyword arguments passed to the validator on every call. | {} |
- Guide
- Sources API keys and Basic API keys
- The sources
authenticate async ¶
authenticate(
credential: str,
*,
request: HTTPConnection | None = None,
) -> Any
Validate a credential and return the identity, ignoring route scopes.
www_authenticate ¶
www_authenticate() -> str | None
Return the WWW-Authenticate challenge sent with this source's 401s.
Returns:
| Type | Description |
|---|---|
str | None | The challenge, or |
authenticate_scoped async ¶
authenticate_scoped(
credential: str,
scopes: list[str],
*,
request: HTTPConnection | None = None,
) -> Any
Validate a credential, passing the route's scopes and request on.
optional ¶
optional() -> Self
Return a copy that yields None instead of a 401 when no credential is sent.
A credential that is sent and refused still gets its 401 or 403.
Raises:
| Type | Description |
|---|---|
ValueError | On a copy made by |
authenticated_at ¶
Return when a credential was proven, for fresh().
Override it in a source that can date its own credentials, as the signed cookie does. It runs on every authenticated request, whether or not the route asks for freshness, since ensure_fresh() may ask later: return None rather than raise for a credential it cannot date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | Epoch seconds or a |
fresh ¶
fresh(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Self
Return a copy that refuses a credential proven more than max_age ago.
The refusal is a 401 with the RFC 9470 max_age challenge. Composes with stepped_up() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | Sync or async callable taking the identity and returning when it was proven, as epoch seconds or a | None |
leeway | float | Clock-skew tolerance in seconds. It applies both ways: an instant further than | 0.0 |
Raises:
| Type | Description |
|---|---|
ValueError | If |
authenticated ¶
authenticated(request: HTTPConnection) -> bool
Whether this source, or a copy of it, authenticated request.
Lets a route served by several sources tell which one was used, e.g. to check freshness only for a cookie session.
ensure_fresh async ¶
ensure_fresh(
request: HTTPConnection,
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> None
Refuse request if this source authenticated it more than max_age ago.
The fresh() check, for a handler that only knows once the body is parsed whether it needs a recent login. It reads what this source recorded when it authenticated the request: the validator never runs again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request this source authenticated. | required |
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | As in | None |
leeway | float | As in | 0.0 |
Raises:
| Type | Description |
|---|---|
StaleCredentialError | If the credential is too old or cannot be dated, with the same |
UnauthorizedError | If the request carries no credential for this source. |
RuntimeError | If it carries one this source did not authenticate. |
ValueError | As |
fresh_guard ¶
fresh_guard(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Callable[[HTTPConnection], Awaitable[None]]
Return a dependency running ensure_fresh(), for a whole route.
Unlike fresh(), it adds a check after the route's own auth dependency instead of replacing it, so the validator runs once. It must come after that dependency: a parameter after it, or later in the same dependencies=[...] list.
Raises:
| Type | Description |
|---|---|
ValueError | As |
authenticated_acr ¶
Return the acr a credential was proven at, for stepped_up().
Override it in a source that carries the level in its own credentials, as the signed cookie does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | The level, |
stepped_up ¶
Return a copy that refuses a credential not proven at one of acr_values.
The refusal is a 401 with the RFC 9470 acr_values challenge. Composes with fresh() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
acr_values | Sequence[str] | The accepted authentication context class references; any one of them passes. | required |
acr | Callable[..., Any] | None | Sync or async callable taking the identity and returning the | None |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
dispatch async ¶
dispatch(request: HTTPConnection, scopes: list[str]) -> Any
Authenticate a request: extract the credential, then validate it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request or WebSocket being authenticated. | required |
scopes | list[str] | The scopes declared on the route. | required |
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If no credential is present. Every 401 carries this source's |
RuntimeError | If an |
require ¶
Return a copy that passes extra keyword arguments to the validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs | Any | Keyword arguments added to, or overriding, the source's own. | {} |
Raises:
| Type | Description |
|---|---|
ValueError | If a reserved name ( |
extract async ¶
extract(request: HTTPConnection) -> str | None
Return the header value, or None when absent or empty.
fastapi_multiauth.APIKeyQueryAuth ¶
APIKeyQueryAuth(
name: str,
validator: Callable[..., Any],
*,
scheme_name: str | None = None,
description: str | None = None,
**kwargs: Any,
)
Bases: ValidatedAuthSource
Authentication source for an API key in the query string.
Warning
Query strings end up in access logs, browser history and Referer headers. Use this only for clients that cannot set a header.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Query parameter name, e.g. | required |
validator | Callable[..., Any] | Sync or async callable returning the identity, or raising to refuse. | required |
scheme_name | str | None | Name of the security scheme in OpenAPI, | None |
description | str | None | Description of the security scheme in OpenAPI. | None |
**kwargs | Any | Keyword arguments passed to the validator on every call. | {} |
- Guide
- Sources API keys and Basic API keys
- The sources
authorization_scheme class-attribute instance-attribute ¶
authorization_scheme: str | None = None
The Authorization scheme this source reads, lowercased: "*" for any scheme, None when it does not read the header. Under MultiAuth, a header of a scheme a source reads, which no such source takes, is refused instead of passing to a cookie or an API key.
authenticate async ¶
authenticate(
credential: str,
*,
request: HTTPConnection | None = None,
) -> Any
Validate a credential and return the identity, ignoring route scopes.
www_authenticate ¶
www_authenticate() -> str | None
Return the WWW-Authenticate challenge sent with this source's 401s.
Returns:
| Type | Description |
|---|---|
str | None | The challenge, or |
authenticate_scoped async ¶
authenticate_scoped(
credential: str,
scopes: list[str],
*,
request: HTTPConnection | None = None,
) -> Any
Validate a credential, passing the route's scopes and request on.
optional ¶
optional() -> Self
Return a copy that yields None instead of a 401 when no credential is sent.
A credential that is sent and refused still gets its 401 or 403.
Raises:
| Type | Description |
|---|---|
ValueError | On a copy made by |
authenticated_at ¶
Return when a credential was proven, for fresh().
Override it in a source that can date its own credentials, as the signed cookie does. It runs on every authenticated request, whether or not the route asks for freshness, since ensure_fresh() may ask later: return None rather than raise for a credential it cannot date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | Epoch seconds or a |
fresh ¶
fresh(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Self
Return a copy that refuses a credential proven more than max_age ago.
The refusal is a 401 with the RFC 9470 max_age challenge. Composes with stepped_up() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | Sync or async callable taking the identity and returning when it was proven, as epoch seconds or a | None |
leeway | float | Clock-skew tolerance in seconds. It applies both ways: an instant further than | 0.0 |
Raises:
| Type | Description |
|---|---|
ValueError | If |
authenticated ¶
authenticated(request: HTTPConnection) -> bool
Whether this source, or a copy of it, authenticated request.
Lets a route served by several sources tell which one was used, e.g. to check freshness only for a cookie session.
ensure_fresh async ¶
ensure_fresh(
request: HTTPConnection,
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> None
Refuse request if this source authenticated it more than max_age ago.
The fresh() check, for a handler that only knows once the body is parsed whether it needs a recent login. It reads what this source recorded when it authenticated the request: the validator never runs again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request this source authenticated. | required |
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | As in | None |
leeway | float | As in | 0.0 |
Raises:
| Type | Description |
|---|---|
StaleCredentialError | If the credential is too old or cannot be dated, with the same |
UnauthorizedError | If the request carries no credential for this source. |
RuntimeError | If it carries one this source did not authenticate. |
ValueError | As |
fresh_guard ¶
fresh_guard(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Callable[[HTTPConnection], Awaitable[None]]
Return a dependency running ensure_fresh(), for a whole route.
Unlike fresh(), it adds a check after the route's own auth dependency instead of replacing it, so the validator runs once. It must come after that dependency: a parameter after it, or later in the same dependencies=[...] list.
Raises:
| Type | Description |
|---|---|
ValueError | As |
authenticated_acr ¶
Return the acr a credential was proven at, for stepped_up().
Override it in a source that carries the level in its own credentials, as the signed cookie does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | The level, |
stepped_up ¶
Return a copy that refuses a credential not proven at one of acr_values.
The refusal is a 401 with the RFC 9470 acr_values challenge. Composes with fresh() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
acr_values | Sequence[str] | The accepted authentication context class references; any one of them passes. | required |
acr | Callable[..., Any] | None | Sync or async callable taking the identity and returning the | None |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
dispatch async ¶
dispatch(request: HTTPConnection, scopes: list[str]) -> Any
Authenticate a request: extract the credential, then validate it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request or WebSocket being authenticated. | required |
scopes | list[str] | The scopes declared on the route. | required |
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If no credential is present. Every 401 carries this source's |
RuntimeError | If an |
require ¶
Return a copy that passes extra keyword arguments to the validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs | Any | Keyword arguments added to, or overriding, the source's own. | {} |
Raises:
| Type | Description |
|---|---|
ValueError | If a reserved name ( |
extract async ¶
extract(request: HTTPConnection) -> str | None
Return the query parameter value, or None when absent or empty.
fastapi_multiauth.HTTPBasicAuth ¶
HTTPBasicAuth(
validator: Callable[..., Any],
*,
realm: str | None = None,
scheme_name: str | None = None,
description: str | None = None,
**kwargs: Any,
)
Bases: ValidatedAuthSource
Authentication source for HTTP Basic credentials.
Decodes the header as RFC 7617 defines it and calls the validator with username, password. Compare secrets with secrets.compare_digest, never ==.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validator | Callable[..., Any] | Sync or async callable taking | required |
realm | str | None | Realm sent in the | None |
scheme_name | str | None | Name of the security scheme in OpenAPI, | None |
description | str | None | Description of the security scheme in OpenAPI. | None |
**kwargs | Any | Keyword arguments passed to the validator on every call. | {} |
- Guide
- Sources API keys and Basic Basic auth
- The sources
authenticate async ¶
authenticate(
credential: str,
*,
request: HTTPConnection | None = None,
) -> Any
Validate a credential and return the identity, ignoring route scopes.
optional ¶
optional() -> Self
Return a copy that yields None instead of a 401 when no credential is sent.
A credential that is sent and refused still gets its 401 or 403.
Raises:
| Type | Description |
|---|---|
ValueError | On a copy made by |
authenticated_at ¶
Return when a credential was proven, for fresh().
Override it in a source that can date its own credentials, as the signed cookie does. It runs on every authenticated request, whether or not the route asks for freshness, since ensure_fresh() may ask later: return None rather than raise for a credential it cannot date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | Epoch seconds or a |
fresh ¶
fresh(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Self
Return a copy that refuses a credential proven more than max_age ago.
The refusal is a 401 with the RFC 9470 max_age challenge. Composes with stepped_up() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | Sync or async callable taking the identity and returning when it was proven, as epoch seconds or a | None |
leeway | float | Clock-skew tolerance in seconds. It applies both ways: an instant further than | 0.0 |
Raises:
| Type | Description |
|---|---|
ValueError | If |
authenticated ¶
authenticated(request: HTTPConnection) -> bool
Whether this source, or a copy of it, authenticated request.
Lets a route served by several sources tell which one was used, e.g. to check freshness only for a cookie session.
ensure_fresh async ¶
ensure_fresh(
request: HTTPConnection,
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> None
Refuse request if this source authenticated it more than max_age ago.
The fresh() check, for a handler that only knows once the body is parsed whether it needs a recent login. It reads what this source recorded when it authenticated the request: the validator never runs again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request this source authenticated. | required |
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | As in | None |
leeway | float | As in | 0.0 |
Raises:
| Type | Description |
|---|---|
StaleCredentialError | If the credential is too old or cannot be dated, with the same |
UnauthorizedError | If the request carries no credential for this source. |
RuntimeError | If it carries one this source did not authenticate. |
ValueError | As |
fresh_guard ¶
fresh_guard(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Callable[[HTTPConnection], Awaitable[None]]
Return a dependency running ensure_fresh(), for a whole route.
Unlike fresh(), it adds a check after the route's own auth dependency instead of replacing it, so the validator runs once. It must come after that dependency: a parameter after it, or later in the same dependencies=[...] list.
Raises:
| Type | Description |
|---|---|
ValueError | As |
authenticated_acr ¶
Return the acr a credential was proven at, for stepped_up().
Override it in a source that carries the level in its own credentials, as the signed cookie does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | The level, |
stepped_up ¶
Return a copy that refuses a credential not proven at one of acr_values.
The refusal is a 401 with the RFC 9470 acr_values challenge. Composes with fresh() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
acr_values | Sequence[str] | The accepted authentication context class references; any one of them passes. | required |
acr | Callable[..., Any] | None | Sync or async callable taking the identity and returning the | None |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
dispatch async ¶
dispatch(request: HTTPConnection, scopes: list[str]) -> Any
Authenticate a request: extract the credential, then validate it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request or WebSocket being authenticated. | required |
scopes | list[str] | The scopes declared on the route. | required |
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If no credential is present. Every 401 carries this source's |
RuntimeError | If an |
require ¶
Return a copy that passes extra keyword arguments to the validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs | Any | Keyword arguments added to, or overriding, the source's own. | {} |
Raises:
| Type | Description |
|---|---|
ValueError | If a reserved name ( |
www_authenticate ¶
www_authenticate() -> str
Return the Basic challenge, with the realm when configured.
extract async ¶
extract(request: HTTPConnection) -> str | None
Return the encoded credentials, or None when absent or empty.
Decoding happens in authenticate_scoped(), so a malformed value is a 401 rather than a missing credential.
fastapi_multiauth.HMACSignatureAuth ¶
HMACSignatureAuth(
secret_key: str | Sequence[str],
*,
header: str,
prefix: str = "",
signature_key: str | None = None,
timestamp_key: str | None = None,
timestamp_header: str | None = None,
signed_message: str | None = None,
tolerance: float = 300.0,
replay_check: Callable[[str, float], Any] | None = None,
scheme_name: str | None = None,
description: str | None = None,
)
Bases: AuthSource
Authentication source for requests signed with an HMAC-SHA256 of their body.
Verifies incoming webhooks: the sender signs the raw body, and a timestamp when it sends one, with a secret you share, and puts the hex signature in a header. The route receives the verified body as bytes, and can still declare a JSON body parameter, which FastAPI parses from the same bytes.
The signature header carries either one signature after a prefix (sha256=<signature>), or a comma-separated list of key=value items read with signature_key and timestamp_key (t=<time>,v1=<signature>).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret_key | str | Sequence[str] | Shared secret of at least 16 bytes, or a list to rotate secrets (any of them verifies). | required |
header | str | Header carrying the signature. | required |
prefix | str | Text before the signature in the header, e.g. | '' |
signature_key | str | None | Key of the signatures in a | None |
timestamp_key | str | None | Key of the timestamp in a | None |
timestamp_header | str | None | Header carrying the timestamp, when it travels on its own. | None |
signed_message | str | None | What the sender signs: a template ending with | None |
tolerance | float | How far the timestamp may be from now, in seconds. | 300.0 |
replay_check | Callable[[str, float], Any] | None | Sync or async callable recording a verified request until the epoch time it receives, returning | None |
scheme_name | str | None | Name of the security scheme in OpenAPI, | None |
description | str | None | Description of the security scheme in OpenAPI. | None |
Raises:
| Type | Description |
|---|---|
ValueError | On an invalid configuration, such as a short secret, a |
- Guide
- Sources Signed webhooks Senders
- The sources
www_authenticate ¶
www_authenticate() -> str | None
Return the WWW-Authenticate challenge sent with this source's 401s.
Returns:
| Type | Description |
|---|---|
str | None | The challenge, or |
optional ¶
optional() -> Self
Return a copy that yields None instead of a 401 when no credential is sent.
A credential that is sent and refused still gets its 401 or 403.
Raises:
| Type | Description |
|---|---|
ValueError | On a copy made by |
authenticated_at ¶
Return when a credential was proven, for fresh().
Override it in a source that can date its own credentials, as the signed cookie does. It runs on every authenticated request, whether or not the route asks for freshness, since ensure_fresh() may ask later: return None rather than raise for a credential it cannot date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | Epoch seconds or a |
fresh ¶
fresh(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Self
Return a copy that refuses a credential proven more than max_age ago.
The refusal is a 401 with the RFC 9470 max_age challenge. Composes with stepped_up() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | Sync or async callable taking the identity and returning when it was proven, as epoch seconds or a | None |
leeway | float | Clock-skew tolerance in seconds. It applies both ways: an instant further than | 0.0 |
Raises:
| Type | Description |
|---|---|
ValueError | If |
authenticated ¶
authenticated(request: HTTPConnection) -> bool
Whether this source, or a copy of it, authenticated request.
Lets a route served by several sources tell which one was used, e.g. to check freshness only for a cookie session.
ensure_fresh async ¶
ensure_fresh(
request: HTTPConnection,
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> None
Refuse request if this source authenticated it more than max_age ago.
The fresh() check, for a handler that only knows once the body is parsed whether it needs a recent login. It reads what this source recorded when it authenticated the request: the validator never runs again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request this source authenticated. | required |
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | As in | None |
leeway | float | As in | 0.0 |
Raises:
| Type | Description |
|---|---|
StaleCredentialError | If the credential is too old or cannot be dated, with the same |
UnauthorizedError | If the request carries no credential for this source. |
RuntimeError | If it carries one this source did not authenticate. |
ValueError | As |
fresh_guard ¶
fresh_guard(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Callable[[HTTPConnection], Awaitable[None]]
Return a dependency running ensure_fresh(), for a whole route.
Unlike fresh(), it adds a check after the route's own auth dependency instead of replacing it, so the validator runs once. It must come after that dependency: a parameter after it, or later in the same dependencies=[...] list.
Raises:
| Type | Description |
|---|---|
ValueError | As |
authenticated_acr ¶
Return the acr a credential was proven at, for stepped_up().
Override it in a source that carries the level in its own credentials, as the signed cookie does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | The level, |
stepped_up ¶
Return a copy that refuses a credential not proven at one of acr_values.
The refusal is a 401 with the RFC 9470 acr_values challenge. Composes with fresh() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
acr_values | Sequence[str] | The accepted authentication context class references; any one of them passes. | required |
acr | Callable[..., Any] | None | Sync or async callable taking the identity and returning the | None |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
dispatch async ¶
dispatch(request: HTTPConnection, scopes: list[str]) -> Any
Authenticate a request: extract the credential, then validate it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request or WebSocket being authenticated. | required |
scopes | list[str] | The scopes declared on the route. | required |
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If no credential is present. Every 401 carries this source's |
RuntimeError | If an |
extract async ¶
extract(request: HTTPConnection) -> str | None
Return the signature header, or None when absent or empty.
authenticate async ¶
Refuse: a signature cannot be checked without the request body.
Raises:
| Type | Description |
|---|---|
RuntimeError | Always. Let FastAPI call the source as a dependency. |
authenticate_scoped async ¶
authenticate_scoped(
credential: str,
scopes: list[str],
*,
request: HTTPConnection | None = None,
) -> bytes
Verify the timestamp and signature, and return the request body.
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If the header does not parse ( |
RuntimeError | If the route declares scopes, is a WebSocket, or already consumed the body. |
fastapi_multiauth.OAuth2AuthorizationCodeBearerAuth ¶
OAuth2AuthorizationCodeBearerAuth(
validator: Callable[..., Any],
*,
authorization_url: str,
token_url: str,
refresh_url: str | None = None,
scopes: dict[str, str] | None = None,
allow_dpop_bound: bool = False,
scheme_name: str | None = None,
description: str | None = None,
**kwargs: Any,
)
Bases: _BearerSource
Authentication source for bearer tokens from an authorization-code flow.
The URLs and scopes only describe the flow in OpenAPI, which gives /docs a working Authorize dialog.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validator | Callable[..., Any] | Sync or async callable returning the identity, or raising to refuse. | required |
authorization_url | str | URL of the provider's authorization endpoint. | required |
token_url | str | URL of the provider's token endpoint. | required |
refresh_url | str | None | URL of the provider's refresh endpoint, if any. | None |
scopes | dict[str, str] | None | Available scopes mapped to their descriptions. A route declaring a scope outside this catalogue is refused. | None |
allow_dpop_bound | bool | Accept a DPoP-bound token ( | False |
scheme_name | str | None | Name of the security scheme in OpenAPI, | None |
description | str | None | Description of the security scheme in OpenAPI. | None |
**kwargs | Any | Keyword arguments passed to the validator on every call. | {} |
extract async ¶
extract(request: HTTPConnection) -> str | None
Return the bearer token, or None when absent, empty, or without the prefix.
The Bearer scheme is matched case-insensitively, and the prefix is kept in the returned token.
authenticate async ¶
authenticate(
credential: str,
*,
request: HTTPConnection | None = None,
) -> Any
Validate a credential and return the identity, ignoring route scopes.
authenticate_scoped async ¶
authenticate_scoped(
credential: str,
scopes: list[str],
*,
request: HTTPConnection | None = None,
) -> Any
Validate the token, passing the route's scopes and request on.
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If the token is DPoP-bound ( |
optional ¶
optional() -> Self
Return a copy that yields None instead of a 401 when no credential is sent.
A credential that is sent and refused still gets its 401 or 403.
Raises:
| Type | Description |
|---|---|
ValueError | On a copy made by |
authenticated_at ¶
Return when a credential was proven, for fresh().
Override it in a source that can date its own credentials, as the signed cookie does. It runs on every authenticated request, whether or not the route asks for freshness, since ensure_fresh() may ask later: return None rather than raise for a credential it cannot date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | Epoch seconds or a |
fresh ¶
fresh(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Self
Return a copy that refuses a credential proven more than max_age ago.
The refusal is a 401 with the RFC 9470 max_age challenge. Composes with stepped_up() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | Sync or async callable taking the identity and returning when it was proven, as epoch seconds or a | None |
leeway | float | Clock-skew tolerance in seconds. It applies both ways: an instant further than | 0.0 |
Raises:
| Type | Description |
|---|---|
ValueError | If |
authenticated ¶
authenticated(request: HTTPConnection) -> bool
Whether this source, or a copy of it, authenticated request.
Lets a route served by several sources tell which one was used, e.g. to check freshness only for a cookie session.
ensure_fresh async ¶
ensure_fresh(
request: HTTPConnection,
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> None
Refuse request if this source authenticated it more than max_age ago.
The fresh() check, for a handler that only knows once the body is parsed whether it needs a recent login. It reads what this source recorded when it authenticated the request: the validator never runs again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request this source authenticated. | required |
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | As in | None |
leeway | float | As in | 0.0 |
Raises:
| Type | Description |
|---|---|
StaleCredentialError | If the credential is too old or cannot be dated, with the same |
UnauthorizedError | If the request carries no credential for this source. |
RuntimeError | If it carries one this source did not authenticate. |
ValueError | As |
fresh_guard ¶
fresh_guard(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Callable[[HTTPConnection], Awaitable[None]]
Return a dependency running ensure_fresh(), for a whole route.
Unlike fresh(), it adds a check after the route's own auth dependency instead of replacing it, so the validator runs once. It must come after that dependency: a parameter after it, or later in the same dependencies=[...] list.
Raises:
| Type | Description |
|---|---|
ValueError | As |
authenticated_acr ¶
Return the acr a credential was proven at, for stepped_up().
Override it in a source that carries the level in its own credentials, as the signed cookie does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | The level, |
stepped_up ¶
Return a copy that refuses a credential not proven at one of acr_values.
The refusal is a 401 with the RFC 9470 acr_values challenge. Composes with fresh() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
acr_values | Sequence[str] | The accepted authentication context class references; any one of them passes. | required |
acr | Callable[..., Any] | None | Sync or async callable taking the identity and returning the | None |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
dispatch async ¶
dispatch(request: HTTPConnection, scopes: list[str]) -> Any
Authenticate a request: extract the credential, then validate it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request or WebSocket being authenticated. | required |
scopes | list[str] | The scopes declared on the route. | required |
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If no credential is present. Every 401 carries this source's |
RuntimeError | If an |
require ¶
Return a copy that passes extra keyword arguments to the validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs | Any | Keyword arguments added to, or overriding, the source's own. | {} |
Raises:
| Type | Description |
|---|---|
ValueError | If a reserved name ( |
fastapi_multiauth.OAuth2PasswordBearerAuth ¶
OAuth2PasswordBearerAuth(
validator: Callable[..., Any],
*,
token_url: str,
scopes: dict[str, str] | None = None,
allow_dpop_bound: bool = False,
scheme_name: str | None = None,
description: str | None = None,
**kwargs: Any,
)
Bases: _BearerSource
Authentication source for bearer tokens from a password-grant endpoint.
The URL and scopes only describe the flow in OpenAPI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validator | Callable[..., Any] | Sync or async callable returning the identity, or raising to refuse. | required |
token_url | str | URL of the token endpoint. | required |
scopes | dict[str, str] | None | Available scopes mapped to their descriptions. A route declaring a scope outside this catalogue is refused. | None |
allow_dpop_bound | bool | Accept a DPoP-bound token ( | False |
scheme_name | str | None | Name of the security scheme in OpenAPI, | None |
description | str | None | Description of the security scheme in OpenAPI. | None |
**kwargs | Any | Keyword arguments passed to the validator on every call. | {} |
extract async ¶
extract(request: HTTPConnection) -> str | None
Return the bearer token, or None when absent, empty, or without the prefix.
The Bearer scheme is matched case-insensitively, and the prefix is kept in the returned token.
authenticate async ¶
authenticate(
credential: str,
*,
request: HTTPConnection | None = None,
) -> Any
Validate a credential and return the identity, ignoring route scopes.
authenticate_scoped async ¶
authenticate_scoped(
credential: str,
scopes: list[str],
*,
request: HTTPConnection | None = None,
) -> Any
Validate the token, passing the route's scopes and request on.
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If the token is DPoP-bound ( |
optional ¶
optional() -> Self
Return a copy that yields None instead of a 401 when no credential is sent.
A credential that is sent and refused still gets its 401 or 403.
Raises:
| Type | Description |
|---|---|
ValueError | On a copy made by |
authenticated_at ¶
Return when a credential was proven, for fresh().
Override it in a source that can date its own credentials, as the signed cookie does. It runs on every authenticated request, whether or not the route asks for freshness, since ensure_fresh() may ask later: return None rather than raise for a credential it cannot date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | Epoch seconds or a |
fresh ¶
fresh(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Self
Return a copy that refuses a credential proven more than max_age ago.
The refusal is a 401 with the RFC 9470 max_age challenge. Composes with stepped_up() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | Sync or async callable taking the identity and returning when it was proven, as epoch seconds or a | None |
leeway | float | Clock-skew tolerance in seconds. It applies both ways: an instant further than | 0.0 |
Raises:
| Type | Description |
|---|---|
ValueError | If |
authenticated ¶
authenticated(request: HTTPConnection) -> bool
Whether this source, or a copy of it, authenticated request.
Lets a route served by several sources tell which one was used, e.g. to check freshness only for a cookie session.
ensure_fresh async ¶
ensure_fresh(
request: HTTPConnection,
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> None
Refuse request if this source authenticated it more than max_age ago.
The fresh() check, for a handler that only knows once the body is parsed whether it needs a recent login. It reads what this source recorded when it authenticated the request: the validator never runs again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request this source authenticated. | required |
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | As in | None |
leeway | float | As in | 0.0 |
Raises:
| Type | Description |
|---|---|
StaleCredentialError | If the credential is too old or cannot be dated, with the same |
UnauthorizedError | If the request carries no credential for this source. |
RuntimeError | If it carries one this source did not authenticate. |
ValueError | As |
fresh_guard ¶
fresh_guard(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Callable[[HTTPConnection], Awaitable[None]]
Return a dependency running ensure_fresh(), for a whole route.
Unlike fresh(), it adds a check after the route's own auth dependency instead of replacing it, so the validator runs once. It must come after that dependency: a parameter after it, or later in the same dependencies=[...] list.
Raises:
| Type | Description |
|---|---|
ValueError | As |
authenticated_acr ¶
Return the acr a credential was proven at, for stepped_up().
Override it in a source that carries the level in its own credentials, as the signed cookie does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | The level, |
stepped_up ¶
Return a copy that refuses a credential not proven at one of acr_values.
The refusal is a 401 with the RFC 9470 acr_values challenge. Composes with fresh() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
acr_values | Sequence[str] | The accepted authentication context class references; any one of them passes. | required |
acr | Callable[..., Any] | None | Sync or async callable taking the identity and returning the | None |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
dispatch async ¶
dispatch(request: HTTPConnection, scopes: list[str]) -> Any
Authenticate a request: extract the credential, then validate it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request or WebSocket being authenticated. | required |
scopes | list[str] | The scopes declared on the route. | required |
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If no credential is present. Every 401 carries this source's |
RuntimeError | If an |
require ¶
Return a copy that passes extra keyword arguments to the validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs | Any | Keyword arguments added to, or overriding, the source's own. | {} |
Raises:
| Type | Description |
|---|---|
ValueError | If a reserved name ( |
fastapi_multiauth.OpenIdConnectAuth ¶
OpenIdConnectAuth(
validator: Callable[..., Any],
*,
openid_connect_url: str,
allow_dpop_bound: bool = False,
scheme_name: str | None = None,
description: str | None = None,
**kwargs: Any,
)
Bases: _BearerSource
Authentication source for bearer tokens from an OpenID Connect provider.
/docs reads the flow from the provider's discovery document.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validator | Callable[..., Any] | Sync or async callable returning the identity, or raising to refuse. | required |
openid_connect_url | str | URL of the provider's discovery document. | required |
allow_dpop_bound | bool | Accept a DPoP-bound token ( | False |
scheme_name | str | None | Name of the security scheme in OpenAPI, | None |
description | str | None | Description of the security scheme in OpenAPI. | None |
**kwargs | Any | Keyword arguments passed to the validator on every call. | {} |
extract async ¶
extract(request: HTTPConnection) -> str | None
Return the bearer token, or None when absent, empty, or without the prefix.
The Bearer scheme is matched case-insensitively, and the prefix is kept in the returned token.
authenticate async ¶
authenticate(
credential: str,
*,
request: HTTPConnection | None = None,
) -> Any
Validate a credential and return the identity, ignoring route scopes.
authenticate_scoped async ¶
authenticate_scoped(
credential: str,
scopes: list[str],
*,
request: HTTPConnection | None = None,
) -> Any
Validate the token, passing the route's scopes and request on.
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If the token is DPoP-bound ( |
optional ¶
optional() -> Self
Return a copy that yields None instead of a 401 when no credential is sent.
A credential that is sent and refused still gets its 401 or 403.
Raises:
| Type | Description |
|---|---|
ValueError | On a copy made by |
authenticated_at ¶
Return when a credential was proven, for fresh().
Override it in a source that can date its own credentials, as the signed cookie does. It runs on every authenticated request, whether or not the route asks for freshness, since ensure_fresh() may ask later: return None rather than raise for a credential it cannot date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | Epoch seconds or a |
fresh ¶
fresh(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Self
Return a copy that refuses a credential proven more than max_age ago.
The refusal is a 401 with the RFC 9470 max_age challenge. Composes with stepped_up() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | Sync or async callable taking the identity and returning when it was proven, as epoch seconds or a | None |
leeway | float | Clock-skew tolerance in seconds. It applies both ways: an instant further than | 0.0 |
Raises:
| Type | Description |
|---|---|
ValueError | If |
authenticated ¶
authenticated(request: HTTPConnection) -> bool
Whether this source, or a copy of it, authenticated request.
Lets a route served by several sources tell which one was used, e.g. to check freshness only for a cookie session.
ensure_fresh async ¶
ensure_fresh(
request: HTTPConnection,
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> None
Refuse request if this source authenticated it more than max_age ago.
The fresh() check, for a handler that only knows once the body is parsed whether it needs a recent login. It reads what this source recorded when it authenticated the request: the validator never runs again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request this source authenticated. | required |
max_age | float | Freshness window in seconds. | required |
authenticated_at | Callable[..., Any] | None | As in | None |
leeway | float | As in | 0.0 |
Raises:
| Type | Description |
|---|---|
StaleCredentialError | If the credential is too old or cannot be dated, with the same |
UnauthorizedError | If the request carries no credential for this source. |
RuntimeError | If it carries one this source did not authenticate. |
ValueError | As |
fresh_guard ¶
fresh_guard(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Callable[[HTTPConnection], Awaitable[None]]
Return a dependency running ensure_fresh(), for a whole route.
Unlike fresh(), it adds a check after the route's own auth dependency instead of replacing it, so the validator runs once. It must come after that dependency: a parameter after it, or later in the same dependencies=[...] list.
Raises:
| Type | Description |
|---|---|
ValueError | As |
authenticated_acr ¶
Return the acr a credential was proven at, for stepped_up().
Override it in a source that carries the level in its own credentials, as the signed cookie does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credential | str | The credential returned by | required |
Returns:
| Type | Description |
|---|---|
Any | The level, |
stepped_up ¶
Return a copy that refuses a credential not proven at one of acr_values.
The refusal is a 401 with the RFC 9470 acr_values challenge. Composes with fresh() into one challenge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
acr_values | Sequence[str] | The accepted authentication context class references; any one of them passes. | required |
acr | Callable[..., Any] | None | Sync or async callable taking the identity and returning the | None |
Raises:
| Type | Description |
|---|---|
TypeError | If |
ValueError | If |
dispatch async ¶
dispatch(request: HTTPConnection, scopes: list[str]) -> Any
Authenticate a request: extract the credential, then validate it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request | HTTPConnection | The request or WebSocket being authenticated. | required |
scopes | list[str] | The scopes declared on the route. | required |
Raises:
| Type | Description |
|---|---|
UnauthorizedError | If no credential is present. Every 401 carries this source's |
RuntimeError | If an |
require ¶
Return a copy that passes extra keyword arguments to the validator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs | Any | Keyword arguments added to, or overriding, the source's own. | {} |
Raises:
| Type | Description |
|---|---|
ValueError | If a reserved name ( |
fastapi_multiauth.MultiAuth ¶
MultiAuth(*sources: AuthSource)
Combine several sources on one route.
Sources are tried in order, and the first one that finds a credential decides: an invalid credential is refused, not passed to the next source. A token no source takes, such as one without the expected prefix, is refused too. All sources appear in OpenAPI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*sources | AuthSource | The sources to try, in order. | () |
Raises:
| Type | Description |
|---|---|
TypeError | If a source is not an |
ValueError | If only some sources carry a |
- Guide Getting started Combining sources MultiAuth
www_authenticate ¶
www_authenticate() -> str | None
Return the challenges of all sources, joined, or None when none has one.
optional ¶
optional() -> Self
Return a copy that yields None when no source finds a credential.
Raises:
| Type | Description |
|---|---|
ValueError | On a copy made by |
fresh ¶
fresh(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> MultiAuth
Return a copy whose sources all refuse a credential older than max_age.
Applies AuthSource.fresh() to every source, with the same arguments: an authenticated_at reader replaces each source's own dating, a signed cookie's included. To give sources different readers, call fresh() on each one before combining them.
Raises:
| Type | Description |
|---|---|
ValueError | As |
stepped_up ¶
Return a copy whose sources all require one of acr_values.
Applies AuthSource.stepped_up() to every source, with the same arguments: an acr reader replaces each source's own level, a signed cookie's included. To give sources different readers, call stepped_up() on each one before combining them.
Raises:
| Type | Description |
|---|---|
TypeError | As |
ValueError | As |
authenticated ¶
authenticated(request: HTTPConnection) -> bool
Whether one of the sources, or a copy of it, authenticated request.
ensure_fresh async ¶
ensure_fresh(
request: HTTPConnection,
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> None
Run AuthSource.ensure_fresh() on the source that authenticated request.
Every source must date its credentials unless authenticated_at is given. For "a token, or a recent cookie", call the cookie source's own instead.
Raises:
| Type | Description |
|---|---|
StaleCredentialError | As |
UnauthorizedError | If the request carries no credential for any source. |
RuntimeError | If it carries one no source here authenticated. |
ValueError | As |
fresh_guard ¶
fresh_guard(
max_age: float,
*,
authenticated_at: Callable[..., Any] | None = None,
leeway: float = 0.0,
) -> Callable[[HTTPConnection], Awaitable[None]]
Return a dependency running ensure_fresh(), as AuthSource.fresh_guard().
Raises:
| Type | Description |
|---|---|
ValueError | As |
dispatch async ¶
dispatch(request: HTTPConnection, scopes: list[str]) -> Any
Authenticate with the first source that finds a credential.
Validators¶
Ready-made validators to pass to a source. Guide: JWT and OAuth 2.0 tokens.
fastapi_multiauth.JWTValidator ¶
JWTValidator(
*,
secret: str | None = None,
jwks_url: str | None = None,
algorithms: Sequence[str] | None = None,
audience: str
| Sequence[str]
| AnyAudience
| None = None,
issuer: str | None = None,
leeway: float = 0.0,
required_claims: Sequence[str] = ("exp",),
typ: str | None = None,
scopes_claim: str = "scope",
claims_to_identity: Callable[[dict[str, Any]], Any]
| None = None,
jwks_cache_ttl: float = 3600.0,
jwks_refresh_cooldown: float = 30.0,
timeout: float = DEFAULT_TIMEOUT,
)
Validator for JWTs, to pass to HTTPBearerAuth or an OAuth 2.0 source.
Needs the jwt extra. Give either secret (tokens you sign) or jwks_url (tokens from an identity provider). Keys from a JWKS are cached and refreshed when the provider rotates them; if the provider is down, cached keys keep working, and a cold start answers 503.
A token whose typ or token_use claim marks it as a refresh, ID or logout token is refused (not_access_token), as the introspection validator does. Providers that mark their access tokens in the header can be held to it with typ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret | str | None | Shared HMAC key of at least 32 bytes. | None |
jwks_url | str | None | HTTPS URL of the provider's public keys. | None |
algorithms | Sequence[str] | None | Accepted algorithms; | None |
audience | str | Sequence[str] | AnyAudience | None | Expected | None |
issuer | str | None | Expected | None |
leeway | float | Clock-skew tolerance in seconds for | 0.0 |
required_claims | Sequence[str] | Claims every token must carry. | ('exp',) |
typ | str | None | Expected JWT header | None |
scopes_claim | str | Claim holding granted scopes: a space-separated string ( | 'scope' |
claims_to_identity | Callable[[dict[str, Any]], Any] | None | Sync or async callable turning the verified claims into your identity; the claims are returned otherwise. | None |
jwks_cache_ttl | float | How long fetched keys are cached, in seconds. | 3600.0 |
jwks_refresh_cooldown | float | Minimum delay between key fetches, in seconds. | 30.0 |
timeout | float | Timeout of the key fetch, in seconds. | DEFAULT_TIMEOUT |
Raises:
| Type | Description |
|---|---|
ValueError | On an invalid configuration, such as both or neither of |
- Guide Sources JWT and OAuth 2.0
ANY_AUDIENCE class-attribute ¶
Explicit audience opt-out: accept a token whatever its aud.
fastapi_multiauth.IntrospectionValidator ¶
IntrospectionValidator(
*,
url: str,
client_id: str,
client_secret: str,
audience: str
| Sequence[str]
| AnyAudience
| None = None,
issuer: str | None = None,
leeway: float = 0.0,
scopes_claim: str = "scope",
claims_to_identity: Callable[[dict[str, Any]], Any]
| None = None,
cache_ttl: float = 60.0,
cache_size: int = 10000,
timeout: float = DEFAULT_TIMEOUT,
client: AsyncClient | None = None,
)
Validator asking the provider whether an opaque token is active.
For providers that issue opaque access tokens instead of JWTs. Each new token costs one request to the introspection endpoint, shared by concurrent requests; active answers are cached, so a revoked token keeps working for up to cache_ttl. Refresh and ID tokens are refused. If the endpoint is down, the request is answered with a 503.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url | str | HTTPS URL of the provider's introspection endpoint. | required |
client_id | str | Your client id at the provider. | required |
client_secret | str | Your client secret, sent with HTTP Basic. | required |
audience | str | Sequence[str] | AnyAudience | None | Expected | None |
issuer | str | None | Expected | None |
leeway | float | Clock-skew tolerance in seconds for | 0.0 |
scopes_claim | str | Field holding granted scopes: a space-separated string ( | 'scope' |
claims_to_identity | Callable[[dict[str, Any]], Any] | None | Sync or async callable turning the introspection response into your identity; the response is returned otherwise. | None |
cache_ttl | float | How long an active answer is cached, in seconds, never past the token's | 60.0 |
cache_size | int | How many answers are cached at most. | 10000 |
timeout | float | Timeout of the introspection request, in seconds, when no | DEFAULT_TIMEOUT |
client | AsyncClient | None | An | None |
Raises:
| Type | Description |
|---|---|
ValueError | On an invalid configuration, such as a plain-HTTP |
- Guide Sources JWT and OAuth 2.0 Opaque tokens
ANY_AUDIENCE class-attribute ¶
Explicit audience opt-out: accept a token whatever its aud.
Claims¶
Guide: step-up authentication.
fastapi_multiauth.AuthenticationMethodReference ¶
Bases: StrEnum
The registered values of the amr claim.
Values of the RFC 8176 registry. A StrEnum, so members compare equal to the strings in the claim: AuthenticationMethodReference.HARDWARE_KEY in claims["amr"].
- Guide Going further Step-up authentication Strong login: stepped_up()
FACE class-attribute instance-attribute ¶
Biometric authentication using facial recognition.
FINGERPRINT class-attribute instance-attribute ¶
Biometric authentication using a fingerprint.
GEOLOCATION class-attribute instance-attribute ¶
Use of geolocation information for authentication.
HARDWARE_KEY class-attribute instance-attribute ¶
Proof-of-possession of a hardware-secured key.
IRIS class-attribute instance-attribute ¶
Biometric authentication using an iris scan.
KNOWLEDGE_BASED class-attribute instance-attribute ¶
Knowledge-based authentication.
MULTI_CHANNEL class-attribute instance-attribute ¶
Multiple-channel authentication.
MULTI_FACTOR class-attribute instance-attribute ¶
Multiple-factor authentication.
PIN class-attribute instance-attribute ¶
Personal Identification Number or pattern used to unlock a device.
PROOF_OF_POSSESSION class-attribute instance-attribute ¶
Proof-of-possession of a key (OpenID Connect EAP ACR Values 1.0).
RETINA class-attribute instance-attribute ¶
Biometric authentication using a retina scan.
SMS class-attribute instance-attribute ¶
Confirmation by an SMS text message to a registered number.
SOFTWARE_KEY class-attribute instance-attribute ¶
Proof-of-possession of a software-secured key.
TELEPHONE class-attribute instance-attribute ¶
Confirmation by a telephone call to a registered number.
VOICE class-attribute instance-attribute ¶
Biometric authentication using a voiceprint.
WINDOWS_INTEGRATED class-attribute instance-attribute ¶
Windows integrated authentication.
Introspection¶
Guide: auditing the auth surface.
fastapi_multiauth.auth_surface ¶
Report what guards every route of app.
Reads the routes themselves rather than the OpenAPI schema, so hidden routes are included, and honours app.dependency_overrides, so a guard a test replaced and forgot is reported as not running.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app | FastAPI | The application to inspect. Mounted sub-applications are not inspected; call this on them separately. | required |
Returns:
| Type | Description |
|---|---|
list[RouteAuth] | One |
list[RouteAuth] | documentation and schema routes. A route FastAPI does not manage, |
list[RouteAuth] | such as |
list[RouteAuth] | reported unguarded. |
fastapi_multiauth.RouteAuth dataclass ¶
RouteAuth(
path: str,
methods: tuple[str, ...],
alternatives: tuple[tuple[SchemeRequirement, ...], ...],
scopes: tuple[str, ...],
unguarded: bool,
include_in_schema: bool,
)
What guards one route.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path | str | Full path of the route, router prefix included. | required |
methods | tuple[str, ...] | HTTP methods, sorted; empty for a WebSocket route. | required |
alternatives | tuple[tuple[SchemeRequirement, ...], ...] | The ways to satisfy the route. Entries are alternatives (OR); the schemes inside one entry must all pass (AND). A | required |
scopes | tuple[str, ...] | Every scope named on the route, in first-seen order. What a credential must carry is the scope list of its own entry. | required |
unguarded | bool | Whether a request without a credential reaches the route, including through | required |
include_in_schema | bool | Whether the route appears in | required |
fastapi_multiauth.SchemeRequirement dataclass ¶
SchemeRequirement(
scheme_name: str | None,
source: str,
scopes: tuple[str, ...],
optional: bool | None,
csrf: bool | None = None,
validated: bool = True,
overridden: bool = False,
)
One authentication scheme a route accepts, with the scopes it checks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scheme_name | str | None | OpenAPI security scheme name, | required |
source | str | Class name of the source, e.g. | required |
scopes | tuple[str, ...] | Scopes this scheme checks, in declaration order; the union when the dependency is declared in several places. | required |
optional | bool | None | Whether a request without a credential passes, | required |
csrf | bool | None | Whether the scheme refuses cross-origin requests, as a cookie source does; | None |
validated | bool | Whether a validator checks the credential. | True |
overridden | bool | Whether | False |
Token helpers¶
Guide: issuing and storing tokens.
fastapi_multiauth.hash_token ¶
Return the SHA-256 hex digest of a token, to store instead of the token.
Right for random tokens, which cannot be guessed. Never use it for passwords.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token | str | The token, prefix included. | required |
Returns:
| Type | Description |
|---|---|
str | A 64-character lowercase hex digest. |
fastapi_multiauth.verify_token_hash ¶
fastapi_multiauth.checksum_token_generator ¶
Generate a token body ending in a CRC32 checksum, GitHub-style.
Pass it as HTTPBearerAuth(..., token_generator=checksum_token_generator) and check tokens with verify_token_checksum(). The checksum filters typos; it is not a security mechanism.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nbytes | int | Bytes of random entropy in the body. | 32 |
Returns:
| Type | Description |
|---|---|
str | A base62 body followed by a six-character checksum: 49 characters |
str | at the default |
Raises:
| Type | Description |
|---|---|
ValueError | If |
- Guide Sources Bearer tokens Checksummed tokens
fastapi_multiauth.verify_token_checksum ¶
Check the checksum of a token made by checksum_token_generator().
Call it first in the validator to refuse a typo before the lookup. Anyone can compute a checksum, so passing proves nothing else.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token | str | The token as presented, prefix included. | required |
prefix | str | None | The source's prefix, stripped before the check. | None |
Returns:
| Type | Description |
|---|---|
bool |
|
bool | right checksum. |
Second factor¶
Recipe: two-factor login.
fastapi_multiauth.totp_generate_secret ¶
totp_generate_secret() -> str
Generate a TOTP secret for a user enrolling in a second factor.
Store it encrypted at rest: anyone holding it can compute every code.
Returns:
| Type | Description |
|---|---|
str | 160 random bits in base32, 32 characters. |
fastapi_multiauth.totp_provisioning_uri ¶
Build the otpauth:// URI an authenticator app enrols from.
Follows the Key Uri Format with its defaults (SHA-1, 6 digits, 30 seconds), the only settings every app supports. Render it as a QR code for the user to scan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret | str | The base32 secret from | required |
account | str | The user's account name, such as their email address. | required |
issuer | str | Your service's name, shown in the app. | required |
Returns:
| Type | Description |
|---|---|
str | The provisioning URI. |
Raises:
| Type | Description |
|---|---|
ValueError | If |
fastapi_multiauth.totp_verify ¶
totp_verify(
secret: str,
code: str,
*,
last_step: int | None = None,
window: int = 1,
) -> int | None
Check a TOTP code, refusing one already used.
Store the returned step with the user and pass it back as last_step next time: a code from that step or an earlier one is refused, so a code cannot be replayed within its window. Save it atomically, only if the stored step is still older, e.g. UPDATE ... SET last_step = :step WHERE last_step IS NULL OR last_step < :step, and refuse the login when nothing was updated: two requests carrying the same code would otherwise both read the old step and both pass.
Each guess has three chances in a million at the default window, and nothing here counts them: cap failed attempts per account.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret | str | The user's base32 secret. | required |
code | str | The six digits the user typed, spaces ignored. | required |
last_step | int | None | The step returned by the user's last successful check, | None |
window | int | Steps accepted on each side of the current one, for clock drift. | 1 |
Returns:
| Type | Description |
|---|---|
int | None | The time step the code matched, or |
int | None | is malformed, or is not later than |
Raises:
| Type | Description |
|---|---|
ValueError | If |
Exceptions¶
Guide: status codes.
fastapi_multiauth.UnauthorizedError ¶
Bases: HTTPException
HTTP 401: the credential is missing or invalid.
Raise it from a validator to refuse a credential. The source adds its WWW-Authenticate challenge to the response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
detail | str | Message returned in the response body. | 'Unauthorized' |
headers | dict[str, str] | None | Extra response headers. | None |
- API reference
- Guide Getting started Validators The contract
fastapi_multiauth.ForbiddenError ¶
Bases: HTTPException
HTTP 403: the identity is authenticated, but not allowed here.
Use UnauthorizedError instead when the credential itself is the problem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
detail | str | Message returned in the response body. | 'Forbidden' |
headers | dict[str, str] | None | Extra response headers. | None |
- Guide Getting started Validators The contract
fastapi_multiauth.InsufficientAuthenticationError ¶
InsufficientAuthenticationError(
detail: str = "Insufficient user authentication",
headers: dict[str, str] | None = None,
*,
max_age: float | None = None,
acr_values: tuple[str, ...] | None = None,
)
Bases: UnauthorizedError
HTTP 401: the credential is valid, but not proven strongly enough.
Raised by a route guarded with AuthSource.stepped_up(), and the base class of StaleCredentialError. detail is always "Insufficient user authentication". Sources with an HTTP auth scheme send the RFC 9470 challenge listing every requirement of the route.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
detail | str | Message returned in the response body. | 'Insufficient user authentication' |
headers | dict[str, str] | None | Extra response headers, such as the step-up challenge. | None |
max_age | float | None | The route's freshness window in seconds, if any. | None |
acr_values | tuple[str, ...] | None | The authentication levels the route accepts, if any. | None |
- Guide Going further Step-up authentication Good to know
fastapi_multiauth.StaleCredentialError ¶
StaleCredentialError(
detail: str = "Insufficient user authentication",
headers: dict[str, str] | None = None,
*,
max_age: float | None = None,
acr_values: tuple[str, ...] | None = None,
)
Bases: InsufficientAuthenticationError
HTTP 401: the credential is valid, but was proven too long ago.
Raised by a route guarded with AuthSource.fresh(). Otherwise identical to InsufficientAuthenticationError.
- API reference
-
APIKeyCookieAuthensure_fresh -
APIKeyHeaderAuthensure_fresh -
APIKeyQueryAuthensure_fresh -
AuthSourceensure_fresh -
HMACSignatureAuthensure_fresh -
HTTPBasicAuthensure_fresh -
HTTPBearerAuthensure_fresh -
HTTPDPoPAuthensure_fresh -
MultiAuthensure_fresh -
OAuth2AuthorizationCodeBearerAuthensure_fresh -
OAuth2PasswordBearerAuthensure_fresh -
OpenIdConnectAuthensure_fresh
-
- Guide Going further Step-up authentication Good to know
OAuth helpers¶
The login-flow helpers in fastapi_multiauth.oauth. Guide: OAuth login flow.
fastapi_multiauth.oauth.oauth_resolve_provider_urls async ¶
oauth_resolve_provider_urls(
discovery_url: str, timeout: float = DEFAULT_TIMEOUT
) -> OIDCEndpoints
Fetch a provider's discovery document and return its endpoints.
Results are cached for an hour. The URL must come from your configuration, never from the request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
discovery_url | str | HTTPS URL of the provider's discovery document. | required |
timeout | float | Request timeout in seconds. | DEFAULT_TIMEOUT |
Returns:
| Type | Description |
|---|---|
OIDCEndpoints | The provider's endpoints. |
Raises:
| Type | Description |
|---|---|
ValueError | If |
OAuthDiscoveryError | If the document cannot be fetched, is malformed, lists a non-HTTPS endpoint (plain-HTTP loopback ones only pass from a loopback discovery URL), or names another issuer. |
fastapi_multiauth.oauth.OIDCEndpoints ¶
Bases: NamedTuple
Endpoints read from a provider's discovery document.
Every URL has been checked to be HTTPS (loopback hosts excepted, for a loopback discovery URL), and issuer to match the discovery URL. Optional fields are None when the provider does not advertise them.
fastapi_multiauth.oauth.oauth_generate_state_token ¶
oauth_generate_state_token() -> str
Generate a random CSRF token for the OAuth state parameter.
fastapi_multiauth.oauth.oauth_generate_nonce ¶
oauth_generate_nonce() -> str
Generate a random OpenID Connect nonce.
Store it next to the state token, send it with oauth_build_authorization_redirect(), and pass it to oauth_validate_id_token() on the callback.
fastapi_multiauth.oauth.oauth_generate_pkce_pair ¶
fastapi_multiauth.oauth.oauth_build_authorization_redirect ¶
oauth_build_authorization_redirect(
authorization_url: str,
*,
client_id: str,
scopes: str,
redirect_uri: str,
destination: str,
state_token: str,
code_challenge: str | None = None,
nonce: str | None = None,
) -> RedirectResponse
Return the redirect that sends the user to the provider's login page.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
authorization_url | str | HTTPS URL of the provider's authorization endpoint. | required |
client_id | str | Your application's client id. | required |
scopes | str | Space-separated scopes to request. | required |
redirect_uri | str | Where the provider sends the user back. | required |
destination | str | Where to send the user after login, carried in | required |
state_token | str | CSRF token from | required |
code_challenge | str | None | PKCE challenge from | None |
nonce | str | None | OpenID Connect nonce from | None |
Returns:
| Type | Description |
|---|---|
RedirectResponse | A 303 redirect to the provider, keeping any query string already |
RedirectResponse | in |
Raises:
| Type | Description |
|---|---|
ValueError | If |
fastapi_multiauth.oauth.oauth_encode_state ¶
fastapi_multiauth.oauth.oauth_decode_state ¶
oauth_decode_state(
state: str | None,
*,
expected_state_token: str,
fallback: str,
allowed_hosts: Sequence[str] | None = (),
) -> str
Verify the state of a callback and return the destination it carries.
Pop the stored token from the session before calling this, so a callback cannot be replayed. The comparison is constant-time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state | str | None | The | required |
expected_state_token | str | The token stored before the redirect. An empty token never matches. | required |
fallback | str | Returned when the destination is missing or refused. | required |
allowed_hosts | Sequence[str] | None | Hosts allowed in an absolute destination. The default allows relative paths only; | () |
Returns:
| Type | Description |
|---|---|
str | The destination, or |
Raises:
| Type | Description |
|---|---|
TypeError | If |
OAuthStateError | If no token was stored, or |
fastapi_multiauth.oauth.oauth_exchange_code async ¶
oauth_exchange_code(
*,
token_url: str,
code: str,
client_id: str,
client_secret: str,
redirect_uri: str,
required_scopes: str | None = None,
code_verifier: str | None = None,
token_endpoint_auth_method: TokenEndpointAuthMethod = "client_secret_post",
timeout: float = DEFAULT_TIMEOUT,
client: AsyncClient | None = None,
) -> dict[str, Any]
Exchange an authorization code for tokens.
The exchange itself, PKCE included, is done by httpx-oauth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_url | str | HTTPS URL of the provider's token endpoint. | required |
code | str | The | required |
client_id | str | Your application's client id. | required |
client_secret | str | Your application's client secret. | required |
redirect_uri | str | The redirect URI sent with the authorization request. | required |
required_scopes | str | None | Space-separated scopes the grant must include. | None |
code_verifier | str | None | PKCE verifier from | None |
token_endpoint_auth_method | TokenEndpointAuthMethod | Send the client credentials in the request body ( | 'client_secret_post' |
timeout | float | Request timeout in seconds, unless | DEFAULT_TIMEOUT |
client | AsyncClient | None | An | None |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | The provider's token response: |
dict[str, Any] | was granted. An |
dict[str, Any] |
|
Raises:
| Type | Description |
|---|---|
ValueError | If |
OAuthExchangeError | If the provider refuses or the request fails, the response has no |
fastapi_multiauth.oauth.oauth_fetch_userinfo async ¶
oauth_fetch_userinfo(
*,
userinfo_url: str,
access_token: str,
expected_sub: str | None = None,
timeout: float = DEFAULT_TIMEOUT,
client: AsyncClient | None = None,
) -> dict[str, Any]
Fetch the user's profile from the userinfo endpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
userinfo_url | str | HTTPS URL of the provider's userinfo endpoint. | required |
access_token | str | Access token from | required |
expected_sub | str | None | The | None |
timeout | float | Request timeout in seconds, unless | DEFAULT_TIMEOUT |
client | AsyncClient | None | An | None |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | The JSON profile returned by the provider. |
Raises:
| Type | Description |
|---|---|
ValueError | If |
OAuthUserinfoError | If the request fails, does not return a JSON object, or the profile's |
fastapi_multiauth.oauth.oauth_validate_id_token async ¶
oauth_validate_id_token(
id_token: str,
*,
issuer: str,
jwks_uri: str,
client_id: str,
nonce: str | None = None,
access_token: str | None = None,
algorithms: Sequence[str] = ("RS256", "ES256"),
leeway: float = 0.0,
timeout: float = DEFAULT_TIMEOUT,
) -> dict[str, Any]
Validate an OpenID Connect ID token and return its claims.
Needs the jwt extra too. Checks the signature against the provider's keys (cached as JWTValidator does), iss, aud, azp, exp, iat and sub (OIDC Core 3.1.3.7).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id_token | str | The | required |
issuer | str | Expected | required |
jwks_uri | str | HTTPS URL of the provider's keys ( | required |
client_id | str | Your client id: it must be in | required |
nonce | str | None | The nonce sent with the login, compared in constant time. An empty string never matches; | None |
access_token | str | None | The access token issued alongside, checked against the token's | None |
algorithms | Sequence[str] | Accepted algorithms; | ('RS256', 'ES256') |
leeway | float | Clock-skew tolerance in seconds for | 0.0 |
timeout | float | Timeout of the key fetch, in seconds. | DEFAULT_TIMEOUT |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | The verified claims. |
Raises:
| Type | Description |
|---|---|
ValueError | If |
OAuthIDTokenError | If any check fails, or the keys cannot be fetched and none are cached. |
fastapi_multiauth.oauth.OAuthError ¶
Bases: Exception
Base class of every OAuth login flow error.
Not an HTTPException: your route decides what a failed login returns.
- Guide Going further OAuth login flow 2. Handle the callback
fastapi_multiauth.oauth.OAuthStateError ¶
Bases: OAuthError
The state parameter failed its CSRF check.
The callback does not come from a login this browser started: do not exchange the code.
fastapi_multiauth.oauth.OAuthDiscoveryError ¶
fastapi_multiauth.oauth.OAuthExchangeError ¶
fastapi_multiauth.oauth.OAuthUserinfoError ¶
fastapi_multiauth.oauth.OAuthIDTokenError ¶
Bases: OAuthError
The OpenID Connect ID token failed validation.
Its signature, issuer, audience, lifetime, nonce or at_hash did not check out, or the provider's keys could not be fetched. Do not trust any of its claims.