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 |
required |
prefix
|
str | None
|
Optional token prefix (e.g. |
None
|
**kwargs
|
Any
|
Extra keyword arguments forwarded to the validator on every
call (e.g. |
{}
|
__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 |
32
|
Returns:
| Type | Description |
|---|---|
str
|
A ready-to-use token string (e.g. |
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 |
required |
secret_key
|
str | None
|
When provided, the cookie is HMAC-SHA256 signed.
:meth: |
None
|
ttl
|
int
|
Cookie lifetime in seconds (default 24 h). Only used when
|
86400
|
secure
|
bool
|
Set the |
True
|
**kwargs
|
Any
|
Extra keyword arguments forwarded to the validator on every
call (e.g. |
{}
|
__call__(**kwargs)
async
¶
FastAPI dependency dispatch.
delete_cookie(response)
¶
Clear the session cookie (logout).
require(**kwargs)
¶
Return a new instance with additional (or overriding) validator kwargs.
set_cookie(response, value)
¶
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. |
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: |
required |
**kwargs
|
Any
|
Extra keyword arguments forwarded to the validator on every
call (e.g. |
{}
|
__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 |
required |
Returns:
| Type | Description |
|---|---|
str
|
A |
str
|
userinfo_url is |
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 |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The JSON payload returned by the userinfo endpoint as a plain |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the provider granted a different token type than |
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 |
required |
state_token
|
str
|
CSRF token generated by :func: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
A |
RedirectResponse
|
class: |
RedirectResponse
|
authorization page. |
fastapi_toolsets.security.oauth_encode_state(url, state_token)
¶
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 |
required |
expected_state_token
|
str
|
The token stored before the authorization redirect.
If it does not match the decoded value, |
required |
fallback
|
str
|
URL to return when |
required |
Returns:
| Type | Description |
|---|---|
str
|
The destination URL embedded in |
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.