- Security Tools
- fastapi.security.APIKeyHeader
- model
instance-attribute
- scheme_name
instance-attribute
- auto_error
instance-attribute
- fastapi.security.APIKeyQuery
- model
instance-attribute
- scheme_name
instance-attribute
- auto_error
instance-attribute
- HTTP Authentication Schemes
- fastapi.security.HTTPBasic
- model
instance-attribute
- scheme_name
instance-attribute
- realm
instance-attribute
- auto_error
instance-attribute
- fastapi.security.HTTPBearer
- model
instance-attribute
- scheme_name
instance-attribute
- auto_error
instance-attribute
- fastapi.security.HTTPDigest
- model
instance-attribute
- scheme_name
instance-attribute
- auto_error
instance-attribute
- HTTP Credentials
- fastapi.security.HTTPAuthorizationCredentials
- fastapi.security.HTTPBasicCredentials
- OAuth2 Authentication
- fastapi.security.OAuth2
- fastapi.security.OAuth2AuthorizationCodeBearer
- fastapi.security.OAuth2PasswordBearer
- OAuth2 Password Form
- fastapi.security.OAuth2PasswordRequestForm
- grant_type
instance-attribute
- username
instance-attribute
- password
instance-attribute
- scopes
instance-attribute
- client_id
instance-attribute
- client_secret
instance-attribute
- fastapi.security.OAuth2PasswordRequestFormStrict
- grant_type
instance-attribute
- username
instance-attribute
- password
instance-attribute
- scopes
instance-attribute
- client_id
instance-attribute
- client_secret
instance-attribute
- OAuth2 Security Scopes in Dependencies
- fastapi.security.SecurityScopes
- OpenID Connect
- fastapi.security.OpenIdConnect
Security Tools
When you need to declare dependencies with OAuth2 scopes you use Security()
.
But you still need to define what is the dependable, the callable that you pass as a parameter to Depends()
or Security()
.
There are multiple tools that you can use to create those dependables, and they get integrated into OpenAPI so they are shown in the automatic docs UI, they can be used by automatically generated clients and SDKs, etc.
You can import them from fastapi.security
:
from fastapi.security import (
APIKeyCookie,
APIKeyHeader,
APIKeyQuery,
HTTPAuthorizationCredentials,
HTTPBasic,
HTTPBasicCredentials,
HTTPBearer,
HTTPDigest,
OAuth2,
OAuth2AuthorizationCodeBearer,
OAuth2PasswordBearer,
OAuth2PasswordRequestForm,
OAuth2PasswordRequestFormStrict,
OpenIdConnect,
SecurityScopes,
)
API Key Security Schemes
fastapi.security.APIKeyCookie
APIKeyCookie(
*,
name,
scheme_name=None,
description=None,
auto_error=True
)
Bases: APIKeyBase
API key authentication using a cookie.
This defines the name of the cookie that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the cookie automatically and provides it as the dependency result. But it doesn’t define how to set that cookie.
Usage
Create an instance object and use that object as the dependency in Depends()
.
The dependency result will be a string containing the key value.
Example
from fastapi import Depends, FastAPI
from fastapi.security import APIKeyCookie
app = FastAPI()
cookie_scheme = APIKeyCookie(name="session")
@app.get("/items/")
async def read_items(session: str = Depends(cookie_scheme)):
return {"session": session}
PARAMETER | DESCRIPTION |
---|---|
name | Cookie name. TYPE: |
scheme_name | Security scheme name. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
description | Security scheme description. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
auto_error | By default, if the cookie is not provided, If This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a cookie or in an HTTP Bearer token). TYPE: |
Source code in fastapi/security/api_key.py
|
|
model instance-attribute
scheme_name instance-attribute
scheme_name = scheme_name or __name__
auto_error instance-attribute
auto_error = auto_error
fastapi.security.APIKeyHeader
APIKeyHeader(
*,
name,
scheme_name=None,
description=None,
auto_error=True
)
Bases: APIKeyBase
API key authentication using a header.
This defines the name of the header that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the header automatically and provides it as the dependency result. But it doesn’t define how to send that key to the client.
Usage
Create an instance object and use that object as the dependency in Depends()
.
The dependency result will be a string containing the key value.
Example
from fastapi import Depends, FastAPI
from fastapi.security import APIKeyHeader
app = FastAPI()
header_scheme = APIKeyHeader(name="x-key")
@app.get("/items/")
async def read_items(key: str = Depends(header_scheme)):
return {"key": key}
PARAMETER | DESCRIPTION |
---|---|
name | Header name. TYPE: |
scheme_name | Security scheme name. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
description | Security scheme description. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
auto_error | By default, if the header is not provided, If This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a header or in an HTTP Bearer token). TYPE: |
Source code in fastapi/security/api_key.py
|
|
model instance-attribute
scheme_name instance-attribute
scheme_name = scheme_name or __name__
auto_error instance-attribute
auto_error = auto_error
fastapi.security.APIKeyQuery
APIKeyQuery(
*,
name,
scheme_name=None,
description=None,
auto_error=True
)
Bases: APIKeyBase
API key authentication using a query parameter.
This defines the name of the query parameter that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the query parameter automatically and provides it as the dependency result. But it doesn’t define how to send that API key to the client.
Usage
Create an instance object and use that object as the dependency in Depends()
.
The dependency result will be a string containing the key value.
Example
from fastapi import Depends, FastAPI
from fastapi.security import APIKeyQuery
app = FastAPI()
query_scheme = APIKeyQuery(name="api_key")
@app.get("/items/")
async def read_items(api_key: str = Depends(query_scheme)):
return {"api_key": api_key}
PARAMETER | DESCRIPTION |
---|---|
name | Query parameter name. TYPE: |
scheme_name | Security scheme name. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
description | Security scheme description. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
auto_error | By default, if the query parameter is not provided, If This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a query parameter or in an HTTP Bearer token). TYPE: |
Source code in fastapi/security/api_key.py
|
|
model instance-attribute
scheme_name instance-attribute
scheme_name = scheme_name or __name__
auto_error instance-attribute
auto_error = auto_error
HTTP Authentication Schemes
fastapi.security.HTTPBasic
HTTPBasic(
*,
scheme_name=None,
realm=None,
description=None,
auto_error=True
)
Bases: HTTPBase
HTTP Basic authentication.
Usage
Create an instance object and use that object as the dependency in Depends()
.
The dependency result will be an HTTPBasicCredentials
object containing the username
and the password
.
Read more about it in the FastAPI docs for HTTP Basic Auth.
Example
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.security import HTTPBasic, HTTPBasicCredentials
app = FastAPI()
security = HTTPBasic()
@app.get("/users/me")
def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
return {"username": credentials.username, "password": credentials.password}
PARAMETER | DESCRIPTION |
---|---|
scheme_name | Security scheme name. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
realm | HTTP Basic authentication realm. TYPE: |
description | Security scheme description. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
auto_error | By default, if the HTTP Basic authentication is not provided (a header), If This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in HTTP Basic authentication or in an HTTP Bearer token). TYPE: |
Source code in fastapi/security/http.py
|
|
model instance-attribute
model = HTTPBase(scheme='basic', description=description)
scheme_name instance-attribute
scheme_name = scheme_name or __name__
realm instance-attribute
realm = realm
auto_error instance-attribute
auto_error = auto_error
fastapi.security.HTTPBearer
HTTPBearer(
*,
bearerFormat=None,
scheme_name=None,
description=None,
auto_error=True
)
Bases: HTTPBase
HTTP Bearer token authentication.
Usage
Create an instance object and use that object as the dependency in Depends()
.
The dependency result will be an HTTPAuthorizationCredentials
object containing the scheme
and the credentials
.
Example
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
app = FastAPI()
security = HTTPBearer()
@app.get("/users/me")
def read_current_user(
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
):
return {"scheme": credentials.scheme, "credentials": credentials.credentials}
PARAMETER | DESCRIPTION |
---|---|
bearerFormat | Bearer token format. TYPE: |
scheme_name | Security scheme name. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
description | Security scheme description. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
auto_error | By default, if the HTTP Bearer token not provided (in an If This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in an HTTP Bearer token or in a cookie). TYPE: |
Source code in fastapi/security/http.py
|
|
model instance-attribute
model = HTTPBearer(
bearerFormat=bearerFormat, description=description
)
scheme_name instance-attribute
scheme_name = scheme_name or __name__
auto_error instance-attribute
auto_error = auto_error
fastapi.security.HTTPDigest
HTTPDigest(
*, scheme_name=None, description=None, auto_error=True
)
Bases: HTTPBase
HTTP Digest authentication.
Usage
Create an instance object and use that object as the dependency in Depends()
.
The dependency result will be an HTTPAuthorizationCredentials
object containing the scheme
and the credentials
.
Example
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest
app = FastAPI()
security = HTTPDigest()
@app.get("/users/me")
def read_current_user(
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
):
return {"scheme": credentials.scheme, "credentials": credentials.credentials}
PARAMETER | DESCRIPTION |
---|---|
scheme_name | Security scheme name. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
description | Security scheme description. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
auto_error | By default, if the HTTP Digest not provided, If This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in HTTP Digest or in a cookie). TYPE: |
Source code in fastapi/security/http.py
|
|
model instance-attribute
model = HTTPBase(scheme='digest', description=description)
scheme_name instance-attribute
scheme_name = scheme_name or __name__
auto_error instance-attribute
auto_error = auto_error
HTTP Credentials
fastapi.security.HTTPAuthorizationCredentials
Bases: BaseModel
The HTTP authorization credentials in the result of using HTTPBearer
or HTTPDigest
in a dependency.
The HTTP authorization header value is split by the first space.
The first part is the scheme
, the second part is the credentials
.
For example, in an HTTP Bearer token scheme, the client will send a header like:
Authorization: Bearer deadbeef12346
In this case:
scheme
will have the value"Bearer"
credentials
will have the value"deadbeef12346"
scheme instance-attribute
scheme
The HTTP authorization scheme extracted from the header value.
credentials instance-attribute
credentials
The HTTP authorization credentials extracted from the header value.
fastapi.security.HTTPBasicCredentials
Bases: BaseModel
The HTTP Basic credendials given as the result of using HTTPBasic
in a dependency.
Read more about it in the FastAPI docs for HTTP Basic Auth.
username instance-attribute
username
The HTTP Basic username.
password instance-attribute
password
The HTTP Basic password.
OAuth2 Authentication
fastapi.security.OAuth2
OAuth2(
*,
flows=OAuthFlowsModel(),
scheme_name=None,
description=None,
auto_error=True
)
Bases: SecurityBase
This is the base class for OAuth2 authentication, an instance of it would be used as a dependency. All other OAuth2 classes inherit from it and customize it for each OAuth2 flow.
You normally would not create a new class inheriting from it but use one of the existing subclasses, and maybe compose them if you want to support multiple flows.
Read more about it in the FastAPI docs for Security.
PARAMETER | DESCRIPTION |
---|---|
flows | The dictionary of OAuth2 flows. TYPE: |
scheme_name | Security scheme name. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
description | Security scheme description. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
auto_error | By default, if no HTTP Auhtorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. If This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie). TYPE: |
Source code in fastapi/security/oauth2.py
|
|
model instance-attribute
model = OAuth2(
flows=cast(OAuthFlows, flows), description=description
)
scheme_name instance-attribute
scheme_name = scheme_name or __name__
auto_error instance-attribute
auto_error = auto_error
fastapi.security.OAuth2AuthorizationCodeBearer
OAuth2AuthorizationCodeBearer(
authorizationUrl,
tokenUrl,
refreshUrl=None,
scheme_name=None,
scopes=None,
description=None,
auto_error=True,
)
Bases: [OAuth2](#fastapi.security.OAuth2 "fastapi.security.oauth2.OAuth2")
OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code flow. An instance of it would be used as a dependency.
PARAMETER | DESCRIPTION |
---|---|
authorizationUrl | TYPE: |
tokenUrl | The URL to obtain the OAuth2 token. TYPE: |
refreshUrl | The URL to refresh the token and obtain a new one. TYPE: |
scheme_name | Security scheme name. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
scopes | The OAuth2 scopes that would be required by the path operations that use this dependency. TYPE: |
description | Security scheme description. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
auto_error | By default, if no HTTP Auhtorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. If This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie). TYPE: |
Source code in fastapi/security/oauth2.py
|
|
model instance-attribute
model = OAuth2(
flows=cast(OAuthFlows, flows), description=description
)
scheme_name instance-attribute
scheme_name = scheme_name or __name__
auto_error instance-attribute
auto_error = auto_error
fastapi.security.OAuth2PasswordBearer
OAuth2PasswordBearer(
tokenUrl,
scheme_name=None,
scopes=None,
description=None,
auto_error=True,
)
Bases: [OAuth2](#fastapi.security.OAuth2 "fastapi.security.oauth2.OAuth2")
OAuth2 flow for authentication using a bearer token obtained with a password. An instance of it would be used as a dependency.
Read more about it in the FastAPI docs for Simple OAuth2 with Password and Bearer.
PARAMETER | DESCRIPTION |
---|---|
tokenUrl | The URL to obtain the OAuth2 token. This would be the path operation that has TYPE: |
scheme_name | Security scheme name. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
scopes | The OAuth2 scopes that would be required by the path operations that use this dependency. TYPE: |
description | Security scheme description. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
auto_error | By default, if no HTTP Auhtorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. If This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie). TYPE: |
Source code in fastapi/security/oauth2.py
|
|
model instance-attribute
model = OAuth2(
flows=cast(OAuthFlows, flows), description=description
)
scheme_name instance-attribute
scheme_name = scheme_name or __name__
auto_error instance-attribute
auto_error = auto_error
OAuth2 Password Form
fastapi.security.OAuth2PasswordRequestForm
OAuth2PasswordRequestForm(
*,
grant_type=None,
username,
password,
scope="",
client_id=None,
client_secret=None
)
This is a dependency class to collect the username
and password
as form data for an OAuth2 password flow.
The OAuth2 specification dictates that for a password flow the data should be collected using form data (instead of JSON) and that it should have the specific fields username
and password
.
All the initialization parameters are extracted from the request.
Read more about it in the FastAPI docs for Simple OAuth2 with Password and Bearer.
Example
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordRequestForm
app = FastAPI()
@app.post("/login")
def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
data = {}
data["scopes"] = []
for scope in form_data.scopes:
data["scopes"].append(scope)
if form_data.client_id:
data["client_id"] = form_data.client_id
if form_data.client_secret:
data["client_secret"] = form_data.client_secret
return data
Note that for OAuth2 the scope items:read
is a single scope in an opaque string. You could have custom internal logic to separate it by colon caracters (:
) or similar, and get the two parts items
and read
. Many applications do that to group and organize permisions, you could do it as well in your application, just know that that it is application specific, it’s not part of the specification.
PARAMETER | DESCRIPTION |
---|---|
grant_type | The OAuth2 spec says it is required and MUST be the fixed string “password”. Nevertheless, this dependency class is permissive and allows not passing it. If you want to enforce it, use instead the TYPE: |
username |
TYPE: |
password |
TYPE: |
scope | A single string with actually several scopes separated by spaces. Each scope is also a string. For example, a single string with: ```python “items:read items:write users:read profile openid” ```` would represent the scopes:
TYPE: |
client_id | If there’s a TYPE: |
client_secret | If there’s a TYPE: |
Source code in fastapi/security/oauth2.py
|
|
grant_type instance-attribute
grant_type = grant_type
username instance-attribute
username = username
password instance-attribute
password = password
scopes instance-attribute
scopes = split()
client_id instance-attribute
client_id = client_id
client_secret instance-attribute
client_secret = client_secret
fastapi.security.OAuth2PasswordRequestFormStrict
OAuth2PasswordRequestFormStrict(
grant_type,
username,
password,
scope="",
client_id=None,
client_secret=None,
)
Bases: [OAuth2PasswordRequestForm](#fastapi.security.OAuth2PasswordRequestForm "fastapi.security.oauth2.OAuth2PasswordRequestForm")
This is a dependency class to collect the username
and password
as form data for an OAuth2 password flow.
The OAuth2 specification dictates that for a password flow the data should be collected using form data (instead of JSON) and that it should have the specific fields username
and password
.
All the initialization parameters are extracted from the request.
The only difference between OAuth2PasswordRequestFormStrict
and OAuth2PasswordRequestForm
is that OAuth2PasswordRequestFormStrict
requires the client to send the form field grant_type
with the value "password"
, which is required in the OAuth2 specification (it seems that for no particular reason), while for OAuth2PasswordRequestForm
grant_type
is optional.
Read more about it in the FastAPI docs for Simple OAuth2 with Password and Bearer.
Example
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordRequestForm
app = FastAPI()
@app.post("/login")
def login(form_data: Annotated[OAuth2PasswordRequestFormStrict, Depends()]):
data = {}
data["scopes"] = []
for scope in form_data.scopes:
data["scopes"].append(scope)
if form_data.client_id:
data["client_id"] = form_data.client_id
if form_data.client_secret:
data["client_secret"] = form_data.client_secret
return data
Note that for OAuth2 the scope items:read
is a single scope in an opaque string. You could have custom internal logic to separate it by colon caracters (:
) or similar, and get the two parts items
and read
. Many applications do that to group and organize permisions, you could do it as well in your application, just know that that it is application specific, it’s not part of the specification.
the OAuth2 spec says it is required and MUST be the fixed string “password”.
This dependency is strict about it. If you want to be permissive, use instead the OAuth2PasswordRequestForm dependency class.
username: username string. The OAuth2 spec requires the exact field name “username”. password: password string. The OAuth2 spec requires the exact field name “password”. scope: Optional string. Several scopes (each one a string) separated by spaces. E.g. “items:read items:write users:read profile openid” client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any) using HTTP Basic auth, as: client_id:client_secret client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any) using HTTP Basic auth, as: client_id:client_secret
PARAMETER | DESCRIPTION |
---|---|
grant_type | The OAuth2 spec says it is required and MUST be the fixed string “password”. This dependency is strict about it. If you want to be permissive, use instead the TYPE: |
username |
TYPE: |
password |
TYPE: |
scope | A single string with actually several scopes separated by spaces. Each scope is also a string. For example, a single string with: ```python “items:read items:write users:read profile openid” ```` would represent the scopes:
TYPE: |
client_id | If there’s a TYPE: |
client_secret | If there’s a TYPE: |
Source code in fastapi/security/oauth2.py
|
|
grant_type instance-attribute
grant_type = grant_type
username instance-attribute
username = username
password instance-attribute
password = password
scopes instance-attribute
scopes = split()
client_id instance-attribute
client_id = client_id
client_secret instance-attribute
client_secret = client_secret
OAuth2 Security Scopes in Dependencies
fastapi.security.SecurityScopes
SecurityScopes(scopes=None)
This is a special class that you can define in a parameter in a dependency to obtain the OAuth2 scopes required by all the dependencies in the same chain.
This way, multiple dependencies can have different scopes, even when used in the same path operation. And with this, you can access all the scopes required in all those dependencies in a single place.
Read more about it in the FastAPI docs for OAuth2 scopes.
PARAMETER | DESCRIPTION |
---|---|
scopes | This will be filled by FastAPI. TYPE: |
Source code in fastapi/security/oauth2.py
|
|
scopes instance-attribute
scopes = scopes or []
The list of all the scopes required by dependencies.
scope_str instance-attribute
scope_str = join(scopes)
All the scopes required by all the dependencies in a single string separated by spaces, as defined in the OAuth2 specification.
OpenID Connect
fastapi.security.OpenIdConnect
OpenIdConnect(
*,
openIdConnectUrl,
scheme_name=None,
description=None,
auto_error=True
)
Bases: SecurityBase
OpenID Connect authentication class. An instance of it would be used as a dependency.
PARAMETER | DESCRIPTION |
---|---|
openIdConnectUrl | The OpenID Connect URL. TYPE: |
scheme_name | Security scheme name. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
description | Security scheme description. It will be included in the generated OpenAPI (e.g. visible at TYPE: |
auto_error | By default, if no HTTP Auhtorization header is provided, required for OpenID Connect authentication, it will automatically cancel the request and send the client an error. If This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OpenID Connect or in a cookie). TYPE: |
Source code in fastapi/security/open_id_connect_url.py
|
|
model instance-attribute
model = OpenIdConnect(
openIdConnectUrl=openIdConnectUrl,
description=description,
)
scheme_name instance-attribute
scheme_name = scheme_name or __name__
auto_error instance-attribute
auto_error = auto_error