Skip to main content

Overview

The Security class extends Depends to handle authentication and authorization with support for OAuth2 scopes. It allows you to declare security requirements for your endpoints and automatically validates scopes.

Signature

Parameters

Callable[..., Any] | None
default:"None"
The security scheme callable (e.g., OAuth2PasswordBearer, HTTPBearer, APIKeyHeader). This dependency should return security credentials that can be validated.
bool
default:"True"
Whether to cache the result of the security dependency within the same request. When True, authentication is performed once per request even if used in multiple dependencies.
Literal['function', 'request'] | None
default:"None"
The scope in which the security dependency operates. Inherited from Depends.
Sequence[str] | None
default:"None"
A list of OAuth2 scopes required for this endpoint. These scopes will be validated against the scopes provided in the security credentials. If the required scopes are not present, FastAPI will return a 403 Forbidden response.

Usage

Basic Authentication

OAuth2 with Scopes

Multiple Scopes

API Key Security

Available Security Schemes

FastAPI provides several built-in security schemes that can be used with Security:
  • OAuth2PasswordBearer - OAuth2 with password flow
  • OAuth2AuthorizationCodeBearer - OAuth2 with authorization code flow
  • HTTPBasic - HTTP Basic authentication
  • HTTPBearer - HTTP Bearer token authentication
  • HTTPDigest - HTTP Digest authentication
  • APIKeyQuery - API key in query parameters
  • APIKeyHeader - API key in request headers
  • APIKeyCookie - API key in cookies
  • OpenIdConnect - OpenID Connect authentication

SecurityScopes

The SecurityScopes class is automatically injected when you use scopes with Security. It provides access to the required scopes:

See Also