Skip to content

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 fastapi.security scheme describing the source in OpenAPI. Only its metadata is used; extract() always reads the credential.

None

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

authenticate(credential: str) -> Any

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 None when the scheme has none (cookies, API keys).

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 extract().

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 when called outside one.

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 fresh() or stepped_up().

authenticated_at

authenticated_at(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

Epoch seconds or a datetime, None when the source cannot tell.

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 datetime (naive means UTC). Required when the source cannot date its credentials, and overrides authenticated_at() when given. A None result refuses the request.

None
leeway float

Clock-skew tolerance in seconds. It applies both ways: an instant further than leeway in the future is refused too.

0.0

Raises:

Type Description
ValueError

If max_age is not positive, leeway is negative, either is not finite, the copy is optional() or already has a window, or the credential cannot be dated.

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 fresh(), applied to the recorded identity.

None
leeway float

As in fresh().

0.0

Raises:

Type Description
StaleCredentialError

If the credential is too old or cannot be dated, with the same max_age and challenge as fresh().

UnauthorizedError

If the request carries no credential for this source.

RuntimeError

If it carries one this source did not authenticate.

ValueError

As fresh(), for the arguments.

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 fresh(), for the arguments.

authenticated_acr

authenticated_acr(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

The level, None when the source cannot tell.

stepped_up

stepped_up(
    acr_values: Sequence[str],
    *,
    acr: Callable[..., Any] | None = None,
) -> Self

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 acr it achieved, e.g. lambda claims: claims.get("acr"). Required when the source cannot read the level itself, and overrides authenticated_acr() when given. Any value outside acr_values, None included, refuses the request.

None

Raises:

Type Description
TypeError

If acr_values is a bare string.

ValueError

If acr_values is empty or holds a value that cannot be sent in a header (whitespace, quotes, backslashes, non-ASCII), the copy is optional() or already has levels, or the level cannot be read.

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 WWW-Authenticate challenge.

RuntimeError

If an optional() copy guards a route declaring scopes, which an anonymous caller could never satisfy.

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. "user_". The prefix stays in the token the validator receives.

None
allow_dpop_bound bool

Accept a DPoP-bound token (cnf.jkt) without its proof.

False
scheme_name str | None

Name of the security scheme in OpenAPI, HTTPBearer by default. Give each source its own name when several share an app.

None
description str | None

Description of the security scheme in OpenAPI.

None
bearer_format str | None

Format hint shown in OpenAPI, e.g. "JWT".

None
token_generator Callable[[int], str]

Callable building a token body from nbytes, used by generate_token(). Build it on secrets, never random.

token_urlsafe
**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.

www_authenticate

www_authenticate() -> str

Return the Bearer challenge, as RFC 6750 defines it.

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 (cnf.jkt in the identity, or in the claims a JWTValidator or IntrospectionValidator verified) and allow_dpop_bound is not set (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 fresh() or stepped_up().

authenticated_at

authenticated_at(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

Epoch seconds or a datetime, None when the source cannot tell.

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 datetime (naive means UTC). Required when the source cannot date its credentials, and overrides authenticated_at() when given. A None result refuses the request.

None
leeway float

Clock-skew tolerance in seconds. It applies both ways: an instant further than leeway in the future is refused too.

0.0

Raises:

Type Description
ValueError

If max_age is not positive, leeway is negative, either is not finite, the copy is optional() or already has a window, or the credential cannot be dated.

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 fresh(), applied to the recorded identity.

None
leeway float

As in fresh().

0.0

Raises:

Type Description
StaleCredentialError

If the credential is too old or cannot be dated, with the same max_age and challenge as fresh().

UnauthorizedError

If the request carries no credential for this source.

RuntimeError

If it carries one this source did not authenticate.

ValueError

As fresh(), for the arguments.

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 fresh(), for the arguments.

authenticated_acr

authenticated_acr(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

The level, None when the source cannot tell.

stepped_up

stepped_up(
    acr_values: Sequence[str],
    *,
    acr: Callable[..., Any] | None = None,
) -> Self

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 acr it achieved, e.g. lambda claims: claims.get("acr"). Required when the source cannot read the level itself, and overrides authenticated_acr() when given. Any value outside acr_values, None included, refuses the request.

None

Raises:

Type Description
TypeError

If acr_values is a bare string.

ValueError

If acr_values is empty or holds a value that cannot be sent in a header (whitespace, quotes, backslashes, non-ASCII), the copy is optional() or already has levels, or the level cannot be read.

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 WWW-Authenticate challenge.

RuntimeError

If an optional() copy guards a route declaring scopes, which an anonymous caller could never satisfy.

require

require(**kwargs: Any) -> Self

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 (scopes, session_id, request) is passed.

generate_token

generate_token(nbytes: int = 32) -> str

Generate a new random token, with the source's prefix in front.

Parameters:

Name Type Description Default
nbytes int

Bytes of entropy, passed to token_generator.

32

Returns:

Type Description
str

The token, e.g. "user_Xk3...". Store its hash_token() digest,

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 JWTValidator.

required
replay_check Callable[[str, float], Any] | NoReplayCheck | None

Sync or async callable taking a proof's jti and the epoch time after which it can be forgotten, recording it, and returning False if it was already recorded. Make it atomic, e.g. Redis SET NX EXAT. Pass NO_REPLAY_CHECK to accept a proof replayed within proof_max_age.

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 iat.

5.0
public_origin str | None

The scheme and host clients call, e.g. "https://api.example.com". Set it in production: without it the URL is read from the request, whose Host header the caller chooses, so a proof signed for another service could be replayed here.

None
jkt Callable[..., Any] | None

Sync or async callable taking the identity and returning the thumbprint the token is bound to. Defaults to reading identity["cnf"]["jkt"], right when the identity is the claims. A None result refuses the request.

None
scheme_name str | None

Name of the security scheme in OpenAPI, DPoP by default.

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 replay_check, a symmetric or unknown algorithm, or a public_origin with a path.

NO_REPLAY_CHECK class-attribute

NO_REPLAY_CHECK: NoReplayCheck = NoReplayCheck.NONE

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 fresh() or stepped_up().

authenticated_at

authenticated_at(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

Epoch seconds or a datetime, None when the source cannot tell.

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 datetime (naive means UTC). Required when the source cannot date its credentials, and overrides authenticated_at() when given. A None result refuses the request.

None
leeway float

Clock-skew tolerance in seconds. It applies both ways: an instant further than leeway in the future is refused too.

0.0

Raises:

Type Description
ValueError

If max_age is not positive, leeway is negative, either is not finite, the copy is optional() or already has a window, or the credential cannot be dated.

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 fresh(), applied to the recorded identity.

None
leeway float

As in fresh().

0.0

Raises:

Type Description
StaleCredentialError

If the credential is too old or cannot be dated, with the same max_age and challenge as fresh().

UnauthorizedError

If the request carries no credential for this source.

RuntimeError

If it carries one this source did not authenticate.

ValueError

As fresh(), for the arguments.

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 fresh(), for the arguments.

authenticated_acr

authenticated_acr(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

The level, None when the source cannot tell.

stepped_up

stepped_up(
    acr_values: Sequence[str],
    *,
    acr: Callable[..., Any] | None = None,
) -> Self

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 acr it achieved, e.g. lambda claims: claims.get("acr"). Required when the source cannot read the level itself, and overrides authenticated_acr() when given. Any value outside acr_values, None included, refuses the request.

None

Raises:

Type Description
TypeError

If acr_values is a bare string.

ValueError

If acr_values is empty or holds a value that cannot be sent in a header (whitespace, quotes, backslashes, non-ASCII), the copy is optional() or already has levels, or the level cannot be read.

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 WWW-Authenticate challenge.

RuntimeError

If an optional() copy guards a route declaring scopes, which an anonymous caller could never satisfy.

require

require(**kwargs: Any) -> Self

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 (scopes, session_id, request) is passed.

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 error="invalid_dpop_proof" when the proof is missing or invalid, names another key than the token, or was already used.

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 __Host- name, which a subdomain cannot overwrite.

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 disables signing.

None
session_id bool

Give each session a random id, passed to the validator as session_id, so sessions can be revoked. Needs a secret_key; turning it on or off logs existing sessions out.

False
csrf bool

Refuse cross-origin requests with a 403, judged from the Sec-Fetch-Site and Origin headers browsers send. Applies to every method but GET, HEAD and OPTIONS, and to WebSocket handshakes. A request carrying neither header is refused too, as is authenticate() called outside a request. On by default; turn it off only for a cookie no browser carries.

True
trusted_origins Sequence[str]

Other origins the CSRF check lets through, such as "https://app.example.com". Needs csrf=True.

()
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 SameSite attribute: "lax", "strict" or "none".

'lax'
domain str | None

The Domain attribute. Leave unset for a __Host- cookie.

None
path str

The Path attribute.

'/'
scheme_name str | None

Name of the security scheme in OpenAPI, APIKeyCookie_{name} by default.

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 __Host- name or samesite="none" with settings a browser would refuse.

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.

name property

name: str

The cookie name.

ttl property

ttl: int

The cookie lifetime in seconds, to derive a stored session's expiry from.

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 None when the scheme has none (cookies, API keys).

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() or stepped_up().

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 datetime (naive means UTC). Required when the source cannot date its credentials, and overrides authenticated_at() when given. A None result refuses the request.

None
leeway float

Clock-skew tolerance in seconds. It applies both ways: an instant further than leeway in the future is refused too.

0.0

Raises:

Type Description
ValueError

If max_age is not positive, leeway is negative, either is not finite, the copy is optional() or already has a window, or the credential cannot be dated.

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 fresh(), applied to the recorded identity.

None
leeway float

As in fresh().

0.0

Raises:

Type Description
StaleCredentialError

If the credential is too old or cannot be dated, with the same max_age and challenge as fresh().

UnauthorizedError

If the request carries no credential for this source.

RuntimeError

If it carries one this source did not authenticate.

ValueError

As fresh(), for the arguments.

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 fresh(), for the arguments.

stepped_up

stepped_up(
    acr_values: Sequence[str],
    *,
    acr: Callable[..., Any] | None = None,
) -> Self

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 acr it achieved, e.g. lambda claims: claims.get("acr"). Required when the source cannot read the level itself, and overrides authenticated_acr() when given. Any value outside acr_values, None included, refuses the request.

None

Raises:

Type Description
TypeError

If acr_values is a bare string.

ValueError

If acr_values is empty or holds a value that cannot be sent in a header (whitespace, quotes, backslashes, non-ASCII), the copy is optional() or already has levels, or the level cannot be read.

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 WWW-Authenticate challenge.

RuntimeError

If an optional() copy guards a route declaring scopes, which an anonymous caller could never satisfy.

require

require(**kwargs: Any) -> Self

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 (scopes, session_id, request) is passed.

authenticated_at

authenticated_at(credential: str) -> float | None

Return when the signed cookie was set, None when it does not verify.

authenticated_acr

authenticated_acr(credential: str) -> str | None

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

Return the session id of the request's cookie, without the validator.

Returns:

Type Description
str | None

The id, or None when session_id is off or the cookie is absent,

str | None

expired or forged.

acr_of

acr_of(request: HTTPConnection) -> str | None

Return the acr of the request's cookie, without the validator.

Returns:

Type Description
str | None

The level passed to set_cookie(), or None when none was passed

str | None

or the cookie is absent, expired or forged.

amr_of

amr_of(request: HTTPConnection) -> tuple[str, ...] | None

Return the amr of the request's cookie, without the validator.

Returns:

Type Description
tuple[str, ...] | None

The methods passed to set_cookie(), or None when none were

tuple[str, ...] | None

passed or the cookie is absent, expired or forged.

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(
    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 stepped_up(). Needs a secret_key.

None
amr Sequence[str] | None

The methods the user just authenticated with, e.g. [AuthenticationMethodReference.PASSWORD]. Needs a secret_key.

None

Returns:

Type Description
str | None

The new session id when session_id is on, otherwise None.

Raises:

Type Description
TypeError

If amr is a bare string.

ValueError

If acr or amr is passed without a secret_key, or holds a value with whitespace, quotes, backslashes or non-ASCII characters.

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 None.

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. "X-API-Key".

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, APIKeyHeader_{name} by default.

None
description str | None

Description of the security scheme in OpenAPI.

None
**kwargs Any

Keyword arguments passed to the validator on every call.

{}

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 None when the scheme has none (cookies, API keys).

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 fresh() or stepped_up().

authenticated_at

authenticated_at(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

Epoch seconds or a datetime, None when the source cannot tell.

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 datetime (naive means UTC). Required when the source cannot date its credentials, and overrides authenticated_at() when given. A None result refuses the request.

None
leeway float

Clock-skew tolerance in seconds. It applies both ways: an instant further than leeway in the future is refused too.

0.0

Raises:

Type Description
ValueError

If max_age is not positive, leeway is negative, either is not finite, the copy is optional() or already has a window, or the credential cannot be dated.

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 fresh(), applied to the recorded identity.

None
leeway float

As in fresh().

0.0

Raises:

Type Description
StaleCredentialError

If the credential is too old or cannot be dated, with the same max_age and challenge as fresh().

UnauthorizedError

If the request carries no credential for this source.

RuntimeError

If it carries one this source did not authenticate.

ValueError

As fresh(), for the arguments.

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 fresh(), for the arguments.

authenticated_acr

authenticated_acr(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

The level, None when the source cannot tell.

stepped_up

stepped_up(
    acr_values: Sequence[str],
    *,
    acr: Callable[..., Any] | None = None,
) -> Self

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 acr it achieved, e.g. lambda claims: claims.get("acr"). Required when the source cannot read the level itself, and overrides authenticated_acr() when given. Any value outside acr_values, None included, refuses the request.

None

Raises:

Type Description
TypeError

If acr_values is a bare string.

ValueError

If acr_values is empty or holds a value that cannot be sent in a header (whitespace, quotes, backslashes, non-ASCII), the copy is optional() or already has levels, or the level cannot be read.

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 WWW-Authenticate challenge.

RuntimeError

If an optional() copy guards a route declaring scopes, which an anonymous caller could never satisfy.

require

require(**kwargs: Any) -> Self

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 (scopes, session_id, request) is passed.

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. "api_key".

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, APIKeyQuery_{name} by default.

None
description str | None

Description of the security scheme in OpenAPI.

None
**kwargs Any

Keyword arguments passed to the validator on every call.

{}

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 None when the scheme has none (cookies, API keys).

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 fresh() or stepped_up().

authenticated_at

authenticated_at(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

Epoch seconds or a datetime, None when the source cannot tell.

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 datetime (naive means UTC). Required when the source cannot date its credentials, and overrides authenticated_at() when given. A None result refuses the request.

None
leeway float

Clock-skew tolerance in seconds. It applies both ways: an instant further than leeway in the future is refused too.

0.0

Raises:

Type Description
ValueError

If max_age is not positive, leeway is negative, either is not finite, the copy is optional() or already has a window, or the credential cannot be dated.

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 fresh(), applied to the recorded identity.

None
leeway float

As in fresh().

0.0

Raises:

Type Description
StaleCredentialError

If the credential is too old or cannot be dated, with the same max_age and challenge as fresh().

UnauthorizedError

If the request carries no credential for this source.

RuntimeError

If it carries one this source did not authenticate.

ValueError

As fresh(), for the arguments.

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 fresh(), for the arguments.

authenticated_acr

authenticated_acr(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

The level, None when the source cannot tell.

stepped_up

stepped_up(
    acr_values: Sequence[str],
    *,
    acr: Callable[..., Any] | None = None,
) -> Self

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 acr it achieved, e.g. lambda claims: claims.get("acr"). Required when the source cannot read the level itself, and overrides authenticated_acr() when given. Any value outside acr_values, None included, refuses the request.

None

Raises:

Type Description
TypeError

If acr_values is a bare string.

ValueError

If acr_values is empty or holds a value that cannot be sent in a header (whitespace, quotes, backslashes, non-ASCII), the copy is optional() or already has levels, or the level cannot be read.

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 WWW-Authenticate challenge.

RuntimeError

If an optional() copy guards a route declaring scopes, which an anonymous caller could never satisfy.

require

require(**kwargs: Any) -> Self

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 (scopes, session_id, request) is passed.

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 username, password and returning the identity, or raising to refuse.

required
realm str | None

Realm sent in the WWW-Authenticate challenge.

None
scheme_name str | None

Name of the security scheme in OpenAPI, HTTPBasic by default.

None
description str | None

Description of the security scheme in OpenAPI.

None
**kwargs Any

Keyword arguments passed to the validator on every call.

{}

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 fresh() or stepped_up().

authenticated_at

authenticated_at(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

Epoch seconds or a datetime, None when the source cannot tell.

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 datetime (naive means UTC). Required when the source cannot date its credentials, and overrides authenticated_at() when given. A None result refuses the request.

None
leeway float

Clock-skew tolerance in seconds. It applies both ways: an instant further than leeway in the future is refused too.

0.0

Raises:

Type Description
ValueError

If max_age is not positive, leeway is negative, either is not finite, the copy is optional() or already has a window, or the credential cannot be dated.

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 fresh(), applied to the recorded identity.

None
leeway float

As in fresh().

0.0

Raises:

Type Description
StaleCredentialError

If the credential is too old or cannot be dated, with the same max_age and challenge as fresh().

UnauthorizedError

If the request carries no credential for this source.

RuntimeError

If it carries one this source did not authenticate.

ValueError

As fresh(), for the arguments.

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 fresh(), for the arguments.

authenticated_acr

authenticated_acr(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

The level, None when the source cannot tell.

stepped_up

stepped_up(
    acr_values: Sequence[str],
    *,
    acr: Callable[..., Any] | None = None,
) -> Self

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 acr it achieved, e.g. lambda claims: claims.get("acr"). Required when the source cannot read the level itself, and overrides authenticated_acr() when given. Any value outside acr_values, None included, refuses the request.

None

Raises:

Type Description
TypeError

If acr_values is a bare string.

ValueError

If acr_values is empty or holds a value that cannot be sent in a header (whitespace, quotes, backslashes, non-ASCII), the copy is optional() or already has levels, or the level cannot be read.

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 WWW-Authenticate challenge.

RuntimeError

If an optional() copy guards a route declaring scopes, which an anonymous caller could never satisfy.

require

require(**kwargs: Any) -> Self

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 (scopes, session_id, request) is passed.

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.

authenticate_scoped async

authenticate_scoped(
    credential: str,
    scopes: list[str],
    *,
    request: HTTPConnection | None = None,
) -> Any

Decode the credentials, then pass them on to the validator.

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. "sha256=".

''
signature_key str | None

Key of the signatures in a key=value list header, e.g. "v1". Several items with this key are all tried.

None
timestamp_key str | None

Key of the timestamp in a key=value list header, e.g. "t". Needs signature_key.

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 {body}, naming {timestamp} when a timestamp is configured, e.g. "v0:{timestamp}:{body}". Defaults to {timestamp}.{body} with a timestamp, {body} without.

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 False if it was already recorded. It receives a SHA-256 digest of scheme_name and the signed message, the same whichever key signed it. Needs a timestamp.

None
scheme_name str | None

Name of the security scheme in OpenAPI, APIKeyHeader_{header} by default.

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 tolerance that is not positive, two timestamp sources, a signed_message that leaves the timestamp unsigned, or a replay_check without a timestamp.

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 None when the scheme has none (cookies, API keys).

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() or stepped_up().

authenticated_at

authenticated_at(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

Epoch seconds or a datetime, None when the source cannot tell.

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 datetime (naive means UTC). Required when the source cannot date its credentials, and overrides authenticated_at() when given. A None result refuses the request.

None
leeway float

Clock-skew tolerance in seconds. It applies both ways: an instant further than leeway in the future is refused too.

0.0

Raises:

Type Description
ValueError

If max_age is not positive, leeway is negative, either is not finite, the copy is optional() or already has a window, or the credential cannot be dated.

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 fresh(), applied to the recorded identity.

None
leeway float

As in fresh().

0.0

Raises:

Type Description
StaleCredentialError

If the credential is too old or cannot be dated, with the same max_age and challenge as fresh().

UnauthorizedError

If the request carries no credential for this source.

RuntimeError

If it carries one this source did not authenticate.

ValueError

As fresh(), for the arguments.

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 fresh(), for the arguments.

authenticated_acr

authenticated_acr(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

The level, None when the source cannot tell.

stepped_up

stepped_up(
    acr_values: Sequence[str],
    *,
    acr: Callable[..., Any] | None = None,
) -> Self

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 acr it achieved, e.g. lambda claims: claims.get("acr"). Required when the source cannot read the level itself, and overrides authenticated_acr() when given. Any value outside acr_values, None included, refuses the request.

None

Raises:

Type Description
TypeError

If acr_values is a bare string.

ValueError

If acr_values is empty or holds a value that cannot be sent in a header (whitespace, quotes, backslashes, non-ASCII), the copy is optional() or already has levels, or the level cannot be read.

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 WWW-Authenticate challenge.

RuntimeError

If an optional() copy guards a route declaring scopes, which an anonymous caller could never satisfy.

extract async

extract(request: HTTPConnection) -> str | None

Return the signature header, or None when absent or empty.

authenticate async

authenticate(credential: str) -> Any

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 (malformed), the timestamp is outside tolerance (expired), no signature matches (invalid_signature), or replay_check already saw it (replay).

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 (cnf.jkt) without its proof.

False
scheme_name str | None

Name of the security scheme in OpenAPI, OAuth2AuthorizationCodeBearer by default.

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.

www_authenticate

www_authenticate() -> str

Return the Bearer challenge, as RFC 6750 defines it.

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 (cnf.jkt in the identity, or in the claims a JWTValidator or IntrospectionValidator verified) and allow_dpop_bound is not set (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 fresh() or stepped_up().

authenticated_at

authenticated_at(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

Epoch seconds or a datetime, None when the source cannot tell.

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 datetime (naive means UTC). Required when the source cannot date its credentials, and overrides authenticated_at() when given. A None result refuses the request.

None
leeway float

Clock-skew tolerance in seconds. It applies both ways: an instant further than leeway in the future is refused too.

0.0

Raises:

Type Description
ValueError

If max_age is not positive, leeway is negative, either is not finite, the copy is optional() or already has a window, or the credential cannot be dated.

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 fresh(), applied to the recorded identity.

None
leeway float

As in fresh().

0.0

Raises:

Type Description
StaleCredentialError

If the credential is too old or cannot be dated, with the same max_age and challenge as fresh().

UnauthorizedError

If the request carries no credential for this source.

RuntimeError

If it carries one this source did not authenticate.

ValueError

As fresh(), for the arguments.

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 fresh(), for the arguments.

authenticated_acr

authenticated_acr(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

The level, None when the source cannot tell.

stepped_up

stepped_up(
    acr_values: Sequence[str],
    *,
    acr: Callable[..., Any] | None = None,
) -> Self

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 acr it achieved, e.g. lambda claims: claims.get("acr"). Required when the source cannot read the level itself, and overrides authenticated_acr() when given. Any value outside acr_values, None included, refuses the request.

None

Raises:

Type Description
TypeError

If acr_values is a bare string.

ValueError

If acr_values is empty or holds a value that cannot be sent in a header (whitespace, quotes, backslashes, non-ASCII), the copy is optional() or already has levels, or the level cannot be read.

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 WWW-Authenticate challenge.

RuntimeError

If an optional() copy guards a route declaring scopes, which an anonymous caller could never satisfy.

require

require(**kwargs: Any) -> Self

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 (scopes, session_id, request) is passed.

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 (cnf.jkt) without its proof.

False
scheme_name str | None

Name of the security scheme in OpenAPI, OAuth2PasswordBearer by default.

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.

www_authenticate

www_authenticate() -> str

Return the Bearer challenge, as RFC 6750 defines it.

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 (cnf.jkt in the identity, or in the claims a JWTValidator or IntrospectionValidator verified) and allow_dpop_bound is not set (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 fresh() or stepped_up().

authenticated_at

authenticated_at(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

Epoch seconds or a datetime, None when the source cannot tell.

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 datetime (naive means UTC). Required when the source cannot date its credentials, and overrides authenticated_at() when given. A None result refuses the request.

None
leeway float

Clock-skew tolerance in seconds. It applies both ways: an instant further than leeway in the future is refused too.

0.0

Raises:

Type Description
ValueError

If max_age is not positive, leeway is negative, either is not finite, the copy is optional() or already has a window, or the credential cannot be dated.

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 fresh(), applied to the recorded identity.

None
leeway float

As in fresh().

0.0

Raises:

Type Description
StaleCredentialError

If the credential is too old or cannot be dated, with the same max_age and challenge as fresh().

UnauthorizedError

If the request carries no credential for this source.

RuntimeError

If it carries one this source did not authenticate.

ValueError

As fresh(), for the arguments.

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 fresh(), for the arguments.

authenticated_acr

authenticated_acr(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

The level, None when the source cannot tell.

stepped_up

stepped_up(
    acr_values: Sequence[str],
    *,
    acr: Callable[..., Any] | None = None,
) -> Self

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 acr it achieved, e.g. lambda claims: claims.get("acr"). Required when the source cannot read the level itself, and overrides authenticated_acr() when given. Any value outside acr_values, None included, refuses the request.

None

Raises:

Type Description
TypeError

If acr_values is a bare string.

ValueError

If acr_values is empty or holds a value that cannot be sent in a header (whitespace, quotes, backslashes, non-ASCII), the copy is optional() or already has levels, or the level cannot be read.

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 WWW-Authenticate challenge.

RuntimeError

If an optional() copy guards a route declaring scopes, which an anonymous caller could never satisfy.

require

require(**kwargs: Any) -> Self

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 (scopes, session_id, request) is passed.

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 (cnf.jkt) without its proof.

False
scheme_name str | None

Name of the security scheme in OpenAPI, OpenIdConnect by default.

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.

www_authenticate

www_authenticate() -> str

Return the Bearer challenge, as RFC 6750 defines it.

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 (cnf.jkt in the identity, or in the claims a JWTValidator or IntrospectionValidator verified) and allow_dpop_bound is not set (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 fresh() or stepped_up().

authenticated_at

authenticated_at(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

Epoch seconds or a datetime, None when the source cannot tell.

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 datetime (naive means UTC). Required when the source cannot date its credentials, and overrides authenticated_at() when given. A None result refuses the request.

None
leeway float

Clock-skew tolerance in seconds. It applies both ways: an instant further than leeway in the future is refused too.

0.0

Raises:

Type Description
ValueError

If max_age is not positive, leeway is negative, either is not finite, the copy is optional() or already has a window, or the credential cannot be dated.

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 fresh(), applied to the recorded identity.

None
leeway float

As in fresh().

0.0

Raises:

Type Description
StaleCredentialError

If the credential is too old or cannot be dated, with the same max_age and challenge as fresh().

UnauthorizedError

If the request carries no credential for this source.

RuntimeError

If it carries one this source did not authenticate.

ValueError

As fresh(), for the arguments.

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 fresh(), for the arguments.

authenticated_acr

authenticated_acr(credential: str) -> Any

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 extract().

required

Returns:

Type Description
Any

The level, None when the source cannot tell.

stepped_up

stepped_up(
    acr_values: Sequence[str],
    *,
    acr: Callable[..., Any] | None = None,
) -> Self

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 acr it achieved, e.g. lambda claims: claims.get("acr"). Required when the source cannot read the level itself, and overrides authenticated_acr() when given. Any value outside acr_values, None included, refuses the request.

None

Raises:

Type Description
TypeError

If acr_values is a bare string.

ValueError

If acr_values is empty or holds a value that cannot be sent in a header (whitespace, quotes, backslashes, non-ASCII), the copy is optional() or already has levels, or the level cannot be read.

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 WWW-Authenticate challenge.

RuntimeError

If an optional() copy guards a route declaring scopes, which an anonymous caller could never satisfy.

require

require(**kwargs: Any) -> Self

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 (scopes, session_id, request) is passed.

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 AuthSource, or is a MultiAuth.

ValueError

If only some sources carry a fresh() or stepped_up() guard: the others would let their credentials through unchecked.

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() or stepped_up().

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 AuthSource.fresh(), naming the source at fault.

stepped_up

stepped_up(
    acr_values: Sequence[str],
    *,
    acr: Callable[..., Any] | None = None,
) -> MultiAuth

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 AuthSource.stepped_up().

ValueError

As AuthSource.stepped_up(), naming the source at fault.

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 AuthSource.ensure_fresh().

UnauthorizedError

If the request carries no credential for any source.

RuntimeError

If it carries one no source here authenticated.

ValueError

As AuthSource.ensure_fresh(), naming the source at fault.

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 ensure_fresh().

dispatch async

dispatch(request: HTTPConnection, scopes: list[str]) -> Any

Authenticate with the first source that finds a credential.

require

require(**kwargs: Any) -> MultiAuth

Return a copy passing extra keyword arguments to every validator.

Raises:

Type Description
TypeError

If a source has no require(): its credentials would pass without the requirement.

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; ["HS256"] with a secret, ["RS256", "ES256"] with a JWKS, where HS* is refused.

None
audience str | Sequence[str] | AnyAudience | None

Expected aud: your API's own identifier. Required with a JWKS, since a provider signs every application's tokens with the same keys; pass ANY_AUDIENCE to skip the check on purpose. Do not use the client id of a front-end here: the ID tokens the provider hands that front-end carry it as aud too.

None
issuer str | None

Expected iss; not checked when unset.

None
leeway float

Clock-skew tolerance in seconds for exp, nbf and iat.

0.0
required_claims Sequence[str]

Claims every token must carry.

('exp',)
typ str | None

Expected JWT header typ, e.g. "at+jwt" for a provider issuing RFC 9068 access tokens. Compared case-insensitively, with or without the application/ prefix. Not checked when unset.

None
scopes_claim str

Claim holding granted scopes: a space-separated string (scope) or a list (scp, roles). A missing route scope is a 403.

'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 secret and jwks_url, a short secret, a JWKS without audience, a negative leeway, or an empty typ.

ANY_AUDIENCE class-attribute

ANY_AUDIENCE: AnyAudience = AnyAudience.ANY

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 aud. Required, since the provider answers for every application's tokens; a response without aud is refused. Pass ANY_AUDIENCE to skip the check on purpose.

None
issuer str | None

Expected iss; not checked when unset.

None
leeway float

Clock-skew tolerance in seconds for exp and nbf.

0.0
scopes_claim str

Field holding granted scopes: a space-separated string (scope) or a list. A missing route scope is a 403.

'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 exp. 0 asks the provider on every request.

60.0
cache_size int

How many answers are cached at most.

10000
timeout float

Timeout of the introspection request, in seconds, when no client is given.

DEFAULT_TIMEOUT
client AsyncClient | None

An httpx.AsyncClient to send the requests with, reusing its connections and its own timeout. Without it, each request opens a new client: pass one when tokens change often.

None

Raises:

Type Description
ValueError

On an invalid configuration, such as a plain-HTTP url, a missing audience, or a negative leeway or cache_ttl.

ANY_AUDIENCE class-attribute

ANY_AUDIENCE: AnyAudience = AnyAudience.ANY

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"].

FACE class-attribute instance-attribute

FACE = 'face'

Biometric authentication using facial recognition.

FINGERPRINT class-attribute instance-attribute

FINGERPRINT = 'fpt'

Biometric authentication using a fingerprint.

GEOLOCATION class-attribute instance-attribute

GEOLOCATION = 'geo'

Use of geolocation information for authentication.

HARDWARE_KEY class-attribute instance-attribute

HARDWARE_KEY = 'hwk'

Proof-of-possession of a hardware-secured key.

IRIS class-attribute instance-attribute

IRIS = 'iris'

Biometric authentication using an iris scan.

KNOWLEDGE_BASED class-attribute instance-attribute

KNOWLEDGE_BASED = 'kba'

Knowledge-based authentication.

MULTI_CHANNEL class-attribute instance-attribute

MULTI_CHANNEL = 'mca'

Multiple-channel authentication.

MULTI_FACTOR class-attribute instance-attribute

MULTI_FACTOR = 'mfa'

Multiple-factor authentication.

ONE_TIME_PASSWORD class-attribute instance-attribute

ONE_TIME_PASSWORD = 'otp'

One-time password.

PIN class-attribute instance-attribute

PIN = 'pin'

Personal Identification Number or pattern used to unlock a device.

PROOF_OF_POSSESSION class-attribute instance-attribute

PROOF_OF_POSSESSION = 'pop'

Proof-of-possession of a key (OpenID Connect EAP ACR Values 1.0).

PASSWORD class-attribute instance-attribute

PASSWORD = 'pwd'

Password-based authentication.

RISK_BASED class-attribute instance-attribute

RISK_BASED = 'rba'

Risk-based authentication.

RETINA class-attribute instance-attribute

RETINA = 'retina'

Biometric authentication using a retina scan.

SMART_CARD class-attribute instance-attribute

SMART_CARD = 'sc'

Smart card.

SMS class-attribute instance-attribute

SMS = 'sms'

Confirmation by an SMS text message to a registered number.

SOFTWARE_KEY class-attribute instance-attribute

SOFTWARE_KEY = 'swk'

Proof-of-possession of a software-secured key.

TELEPHONE class-attribute instance-attribute

TELEPHONE = 'tel'

Confirmation by a telephone call to a registered number.

USER_PRESENCE class-attribute instance-attribute

USER_PRESENCE = 'user'

User presence test.

VOICE class-attribute instance-attribute

VOICE = 'vbm'

Biometric authentication using a voiceprint.

WINDOWS_INTEGRATED class-attribute instance-attribute

WINDOWS_INTEGRATED = 'wia'

Windows integrated authentication.

Introspection

Guide: auditing the auth surface.

fastapi_multiauth.auth_surface

auth_surface(app: FastAPI) -> list[RouteAuth]

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 RouteAuth per route, in registration order, but FastAPI's own

list[RouteAuth]

documentation and schema routes. A route FastAPI does not manage,

list[RouteAuth]

such as app.add_route() or a mount, runs no dependency, so it is

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 MultiAuth gives one entry per source; separate Security() dependencies share one, and dependencies that resolve alike count once. Empty when nothing guards the route.

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 optional() sources, a scheme that does not say (optional=None) or a guard replaced in app.dependency_overrides. A plain fastapi.security scheme refuses a missing credential but checks no value: see SchemeRequirement.validated.

required
include_in_schema bool

Whether the route appears in app.openapi(); False for WebSocket routes.

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, None for a source without a fastapi.security scheme.

required
source str

Class name of the source, e.g. "HTTPBearerAuth".

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, None when the scheme does not say. Always False inside a required MultiAuth.

required
csrf bool | None

Whether the scheme refuses cross-origin requests, as a cookie source does; False for one with csrf=False, None when the scheme does not say.

None
validated bool

Whether a validator checks the credential. False for a plain fastapi.security scheme, which only reads the credential and lets any value through, and for a guard replaced in app.dependency_overrides.

True
overridden bool

Whether app.dependency_overrides replaces the guard, so what the route declares is not what runs.

False

Token helpers

Guide: issuing and storing tokens.

fastapi_multiauth.hash_token

hash_token(token: str) -> str

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

verify_token_hash(token: str, stored_hash: str) -> bool

Check a token against a stored hash, in constant time.

Parameters:

Name Type Description Default
token str

The token presented by the client.

required
stored_hash str

The digest stored with hash_token().

required

Returns:

Type Description
bool

True if the token matches.

fastapi_multiauth.checksum_token_generator

checksum_token_generator(nbytes: int = 32) -> str

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 nbytes.

Raises:

Type Description
ValueError

If nbytes is not positive.

fastapi_multiauth.verify_token_checksum

verify_token_checksum(
    token: str, *, prefix: str | None = None
) -> bool

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

True if the token has the prefix, an alphanumeric body, and the

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

totp_provisioning_uri(
    secret: str, account: str, issuer: str
) -> str

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 totp_generate_secret().

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 secret is not base32 or shorter than 128 bits, or account or issuer is empty or contains a colon, the label's separator.

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 before the first.

None
window int

Steps accepted on each side of the current one, for clock drift. 1 accepts the previous and next 30 seconds.

1

Returns:

Type Description
int | None

The time step the code matched, or None when it does not match,

int | None

is malformed, or is not later than last_step.

Raises:

Type Description
ValueError

If secret is not base32 or shorter than 80 bits, or window is negative. Secrets enrolled from 80 bits up still verify; totp_provisioning_uri() refuses new ones below 128.

Exceptions

Guide: status codes.

fastapi_multiauth.UnauthorizedError

UnauthorizedError(
    detail: str = "Unauthorized",
    headers: dict[str, str] | None = None,
)

fastapi_multiauth.ForbiddenError

ForbiddenError(
    detail: str = "Forbidden",
    headers: dict[str, str] | None = None,
)

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

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

error_description class-attribute

error_description: str = (
    "A different authentication level is required"
)

The challenge's error_description for this refusal.

max_age instance-attribute

max_age: float | None = max_age

The route's freshness window in seconds, None without fresh().

acr_values instance-attribute

acr_values: tuple[str, ...] | None = acr_values

The levels the route accepts, None without stepped_up().

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.

max_age instance-attribute

max_age: float | None = max_age

The route's freshness window in seconds, None without fresh().

acr_values instance-attribute

acr_values: tuple[str, ...] | None = acr_values

The levels the route accepts, None without stepped_up().

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 discovery_url is not HTTPS.

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

oauth_generate_pkce_pair() -> tuple[str, str]

Generate a PKCE verifier and its S256 challenge.

See RFC 7636. Send the challenge with the redirect, keep the verifier server-side, and pass it to oauth_exchange_code() on the callback.

Returns:

Type Description
tuple[str, str]

A (code_verifier, code_challenge) tuple.

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 state.

required
state_token str

CSRF token from oauth_generate_state_token().

required
code_challenge str | None

PKCE challenge from oauth_generate_pkce_pair(), sent with code_challenge_method=S256.

None
nonce str | None

OpenID Connect nonce from oauth_generate_nonce().

None

Returns:

Type Description
RedirectResponse

A 303 redirect to the provider, keeping any query string already

RedirectResponse

in authorization_url.

Raises:

Type Description
ValueError

If authorization_url is not HTTPS.

fastapi_multiauth.oauth.oauth_encode_state

oauth_encode_state(url: str, state_token: str) -> str

Encode a destination and a CSRF token into an OAuth state value.

oauth_build_authorization_redirect() calls it for you.

Parameters:

Name Type Description Default
url str

Where to send the user after login.

required
state_token str

CSRF token from oauth_generate_state_token().

required

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 state query parameter of the callback.

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; None disables the check.

()

Returns:

Type Description
str

The destination, or fallback.

Raises:

Type Description
TypeError

If allowed_hosts is a bare string.

OAuthStateError

If no token was stored, or state is missing, malformed or carries another token. Do not exchange the code.

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 code query parameter of the callback.

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 oauth_generate_pkce_pair(). An empty string is refused: it would silently drop PKCE.

None
token_endpoint_auth_method TokenEndpointAuthMethod

Send the client credentials in the request body (client_secret_post) or as HTTP Basic (client_secret_basic).

'client_secret_post'
timeout float

Request timeout in seconds, unless client is given.

DEFAULT_TIMEOUT
client AsyncClient | None

An httpx.AsyncClient to reuse. It is not closed, and its own settings apply.

None

Returns:

Type Description
dict[str, Any]

The provider's token response: access_token and whatever else

dict[str, Any]

was granted. An id_token in it is unverified until

dict[str, Any]

oauth_validate_id_token() checks it.

Raises:

Type Description
ValueError

If token_url is not HTTPS, or code_verifier is empty.

OAuthExchangeError

If the provider refuses or the request fails, the response has no access_token, the token is not a bearer token, or a required scope is missing.

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 oauth_exchange_code().

required
expected_sub str | None

The sub of the validated ID token. The profile is refused unless its own sub is the same, as OIDC Core 5.3.2 requires: with a substituted access token, the provider would answer with someone else's profile. An empty string never matches; None skips the check.

None
timeout float

Request timeout in seconds, unless client is given.

DEFAULT_TIMEOUT
client AsyncClient | None

An httpx.AsyncClient to reuse. It is not closed, and its own settings apply.

None

Returns:

Type Description
dict[str, Any]

The JSON profile returned by the provider.

Raises:

Type Description
ValueError

If userinfo_url is not HTTPS.

OAuthUserinfoError

If the request fails, does not return a JSON object, or the profile's sub is not expected_sub.

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 id_token of the token response.

required
issuer str

Expected iss, compared exactly (OIDCEndpoints.issuer).

required
jwks_uri str

HTTPS URL of the provider's keys (OIDCEndpoints.jwks_uri).

required
client_id str

Your client id: it must be in aud, and equal azp, which must be present when aud lists several audiences.

required
nonce str | None

The nonce sent with the login, compared in constant time. An empty string never matches; None skips the check.

None
access_token str | None

The access token issued alongside, checked against the token's at_hash. Omit it if the provider sends no at_hash.

None
algorithms Sequence[str]

Accepted algorithms; HS* is refused.

('RS256', 'ES256')
leeway float

Clock-skew tolerance in seconds for exp and iat.

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 jwks_uri is not HTTPS, issuer or client_id is empty, algorithms is empty or includes HS*, or leeway is negative.

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.

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

Bases: OAuthError

The provider's discovery document cannot be fetched or is invalid.

fastapi_multiauth.oauth.OAuthExchangeError

Bases: OAuthError

The authorization code exchange failed.

fastapi_multiauth.oauth.OAuthUserinfoError

Bases: OAuthError

The userinfo endpoint failed or returned something other than JSON.

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.