Overview
TheSecurity 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 withSecurity:
OAuth2PasswordBearer- OAuth2 with password flowOAuth2AuthorizationCodeBearer- OAuth2 with authorization code flowHTTPBasic- HTTP Basic authenticationHTTPBearer- HTTP Bearer token authenticationHTTPDigest- HTTP Digest authenticationAPIKeyQuery- API key in query parametersAPIKeyHeader- API key in request headersAPIKeyCookie- API key in cookiesOpenIdConnect- OpenID Connect authentication
SecurityScopes
TheSecurityScopes class is automatically injected when you use scopes with Security. It provides access to the required scopes:
See Also
- Depends - Base dependency injection class
- FastAPI Security Documentation
- OAuth2 Scopes