Skip to content

security

Here's the reference for the authentication helpers provided by the security module.

You can import them directly from fastapi_toolsets.security:

from fastapi_toolsets.security import (
    AuthSource,
    BearerTokenAuth,
    CookieAuth,
    APIKeyHeaderAuth,
    MultiAuth,
    oauth_build_authorization_redirect,
    oauth_decode_state,
    oauth_encode_state,
    oauth_fetch_userinfo,
    oauth_generate_state_token,
    oauth_resolve_provider_urls,
)

fastapi_toolsets.security.AuthSource

Bases: ABC

Abstract base class for authentication sources.

__call__(**kwargs) async

FastAPI dependency dispatch.

__init__()

Set up the default FastAPI dependency signature.

authenticate(credential) abstractmethod async

Validate a credential and return the authenticated identity.

extract(request) abstractmethod async

Extract the raw credential from the request without validating.

fastapi_toolsets.security.BearerTokenAuth

Bases: AuthSource

Bearer token authentication source.

Wraps :class:fastapi.security.HTTPBearer for OpenAPI documentation. The validator is called as await validator(credential, **kwargs) where kwargs are the extra keyword arguments provided at instantiation.

Parameters:

Name Type Description Default
validator Callable[..., Any]

Sync or async callable that receives the credential and any extra keyword arguments, and returns the authenticated identity (e.g. a User model). Should raise :class:~fastapi_toolsets.exceptions.UnauthorizedError on failure.

required
prefix str | None

Optional token prefix (e.g. "user_"). If set, only tokens whose value starts with this prefix are matched. The prefix is kept in the value passed to the validator — store and compare tokens with their prefix included. Use :meth:generate_token to create correctly-prefixed tokens. This enables multiple BearerTokenAuth instances in the same app (e.g. "user_" for user tokens, "org_" for org tokens).

None
**kwargs Any

Extra keyword arguments forwarded to the validator on every call (e.g. role=Role.ADMIN).

{}

__call__(**kwargs) async

FastAPI dependency dispatch.

authenticate(credential) async

Validate a credential and return the identity.

Calls await validator(credential, **kwargs) where kwargs are the extra keyword arguments provided at instantiation.

extract(request) async

Extract the raw credential from the request without validating.

Returns None if no Authorization: Bearer header is present, the token is empty, or the token does not match the configured prefix. The prefix is included in the returned value.

generate_token(nbytes=32)

Generate a secure random token for this auth source.

Returns a URL-safe random token. If a prefix is configured it is prepended — the returned value is what you store in your database and return to the client as-is.

Parameters:

Name Type Description Default
nbytes int

Number of random bytes before base64 encoding. The resulting string is ceil(nbytes * 4 / 3) characters (43 chars for the default 32 bytes). Defaults to 32.

32

Returns:

Type Description
str

A ready-to-use token string (e.g. "user_Xk3...").

require(**kwargs)

Return a new instance with additional (or overriding) validator kwargs.

fastapi_toolsets.security.CookieAuth

Bases: AuthSource

Cookie-based authentication source.

Wraps :class:fastapi.security.APIKeyCookie for OpenAPI documentation. Optionally signs the cookie with HMAC-SHA256 to provide stateless, tamper- proof sessions without any database entry.

Parameters:

Name Type Description Default
name str

Cookie name.

required
validator Callable[..., Any]

Sync or async callable that receives the cookie value (plain, after signature verification when secret_key is set) and any extra keyword arguments, and returns the authenticated identity.

required
secret_key str | None

When provided, the cookie is HMAC-SHA256 signed. :meth:set_cookie embeds an expiry and signs the payload; :meth:extract verifies the signature and expiry before handing the plain value to the validator. When None (default), the raw cookie value is passed to the validator as-is.

None
ttl int

Cookie lifetime in seconds (default 24 h). Only used when secret_key is set.

86400
secure bool

Set the Secure flag on the cookie so it is only transmitted over HTTPS (default True). Set to False only in local development environments where HTTPS is unavailable.

True
**kwargs Any

Extra keyword arguments forwarded to the validator on every call (e.g. role=Role.ADMIN).

{}

__call__(**kwargs) async

FastAPI dependency dispatch.

Clear the session cookie (logout).

require(**kwargs)

Return a new instance with additional (or overriding) validator kwargs.

Attach the cookie to response, signing it when secret_key is set.

fastapi_toolsets.security.APIKeyHeaderAuth

Bases: AuthSource

API key header authentication source.

Wraps :class:fastapi.security.APIKeyHeader for OpenAPI documentation. The validator is called as await validator(api_key, **kwargs) where kwargs are the extra keyword arguments provided at instantiation.

Parameters:

Name Type Description Default
name str

HTTP header name that carries the API key (e.g. "X-API-Key").

required
validator Callable[..., Any]

Sync or async callable that receives the API key and any extra keyword arguments, and returns the authenticated identity. Should raise :class:~fastapi_toolsets.exceptions.UnauthorizedError on failure.

required
**kwargs Any

Extra keyword arguments forwarded to the validator on every call (e.g. role=Role.ADMIN).

{}

__call__(**kwargs) async

FastAPI dependency dispatch.

authenticate(credential) async

Validate a credential and return the identity.

extract(request) async

Extract the API key from the configured header.

require(**kwargs)

Return a new instance with additional (or overriding) validator kwargs.

fastapi_toolsets.security.MultiAuth

Combine multiple authentication sources into a single callable.

Parameters:

Name Type Description Default
*sources AuthSource

Auth source instances to try in order.

()

require(**kwargs)

Return a new :class:MultiAuth with kwargs forwarded to each source.

fastapi_toolsets.security.oauth_resolve_provider_urls(discovery_url) async

Fetch the OIDC discovery document and return endpoint URLs.

Parameters:

Name Type Description Default
discovery_url str

URL of the provider's /.well-known/openid-configuration.

required

Returns:

Type Description
str

A (authorization_url, token_url, userinfo_url) tuple.

str

userinfo_url is None when the provider does not advertise one.

fastapi_toolsets.security.oauth_fetch_userinfo(*, token_url, userinfo_url, code, client_id, client_secret, redirect_uri, required_scopes=None) async

Exchange an authorization code for tokens and return the userinfo payload.

Parameters:

Name Type Description Default
token_url str

Provider's token endpoint.

required
userinfo_url str

Provider's userinfo endpoint.

required
code str

Authorization code received from the provider's callback.

required
client_id str

OAuth application client ID.

required
client_secret str

OAuth application client secret.

required
redirect_uri str

Redirect URI that was used in the authorization request.

required
required_scopes str | None

Space-separated scopes that must be present in the token response scope field (RFC 6749 §3.3). Raises ValueError if the provider granted fewer scopes than requested.

None

Returns:

Type Description
dict[str, Any]

The JSON payload returned by the userinfo endpoint as a plain dict.

Raises:

Type Description
ValueError

If the provider granted a different token type than bearer or did not grant all required_scopes.

fastapi_toolsets.security.oauth_generate_state_token()

Generate a cryptographically random CSRF token for the OAuth state parameter.

fastapi_toolsets.security.oauth_build_authorization_redirect(authorization_url, *, client_id, scopes, redirect_uri, destination, state_token)

Return an OAuth 2.0 authorization RedirectResponse.

Parameters:

Name Type Description Default
authorization_url str

Provider's authorization endpoint.

required
client_id str

OAuth application client ID.

required
scopes str

Space-separated list of requested scopes.

required
redirect_uri str

URI the provider should redirect back to after authorization.

required
destination str

URL the user should be sent to after the full OAuth flow completes (embedded in state).

required
state_token str

CSRF token generated by :func:oauth_generate_state_token. Must be stored server-side (session or signed cookie) and verified via :func:oauth_decode_state on the callback endpoint (RFC 6749 §10.12).

required

Returns:

Name Type Description
A RedirectResponse

class:~fastapi.responses.RedirectResponse to the provider's

RedirectResponse

authorization page.

fastapi_toolsets.security.oauth_encode_state(url, state_token)

Encode a destination URL and CSRF token into an OAuth state parameter.

Parameters:

Name Type Description Default
url str

Post-login destination URL.

required
state_token str

CSRF token from :func:oauth_generate_state_token.

required

fastapi_toolsets.security.oauth_decode_state(state, *, expected_state_token, fallback)

Decode and CSRF-verify an OAuth state parameter.

Uses a constant-time comparison for the CSRF token to prevent timing attacks.

Parameters:

Name Type Description Default
state str | None

Raw state query parameter from the provider's callback.

required
expected_state_token str

The token stored before the authorization redirect. If it does not match the decoded value, fallback is returned.

required
fallback str

URL to return when state is absent, malformed, or fails CSRF verification.

required

Returns:

Type Description
str

The destination URL embedded in state, or fallback.

Important

Single-use: delete the stored token from the session immediately after calling this function — whether it matched or not — so that a captured callback URL cannot be replayed.

Open-redirect: validate the returned URL against a known-good origin or relative-path allowlist before issuing the final redirect. Do not forward arbitrary URLs to RedirectResponse.