- API Key Security Schemes
APIKeyCookieAPIKeyHeaderAPIKeyQuery- HTTP Authentication Schemes
HTTPBasicHTTPBearerHTTPDigest- HTTP Credentials
HTTPAuthorizationCredentialsHTTPBasicCredentials- OAuth2 Authentication
OAuth2OAuth2AuthorizationCodeBearerOAuth2PasswordBearer- OAuth2 Password Form
OAuth2PasswordRequestFormOAuth2PasswordRequestFormStrict- OAuth2 Security Scopes in Dependencies
SecurityScopes- OpenID Connect
OpenIdConnect
Security Tools¶
When you need to declare dependencies with OAuth2 scopes you useSecurity().
But you still need to define what is the dependable, the callable that you pass as a parameter toDepends() orSecurity().
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 fromfastapi.security:
fromfastapi.securityimport(APIKeyCookie,APIKeyHeader,APIKeyQuery,HTTPAuthorizationCredentials,HTTPBasic,HTTPBasicCredentials,HTTPBearer,HTTPDigest,OAuth2,OAuth2AuthorizationCodeBearer,OAuth2PasswordBearer,OAuth2PasswordRequestForm,OAuth2PasswordRequestFormStrict,OpenIdConnect,SecurityScopes,)Read more about them in theFastAPI docs about Security.
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 withthe API key and integrates that into the OpenAPI documentation. It extractsthe key value sent in the cookie automatically and provides it as the dependencyresult. But it doesn't define how to set that cookie.
Usage¶
Create an instance object and use that object as the dependency inDepends().
The dependency result will be a string containing the key value.
Example¶
fromfastapiimportDepends,FastAPIfromfastapi.securityimportAPIKeyCookieapp=FastAPI()cookie_scheme=APIKeyCookie(name="session")@app.get("/items/")asyncdefread_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 beprovided in one of multiple optional ways (for example, in a cookie orin an HTTP Bearer token). TYPE: |
Source code infastapi/security/api_key.py
265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314 | |
scheme_nameinstance-attribute¶
scheme_name=scheme_nameor__name__auto_errorinstance-attribute¶
auto_error=auto_errormake_not_authenticated_error¶
make_not_authenticated_error()The WWW-Authenticate header is not standardized for API Key authentication butthe HTTP specification requires that an error of 401 "Unauthorized" mustinclude a WWW-Authenticate header.
Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized
For this, this method sends a custom challengeAPIKey.
Source code infastapi/security/api_key.py
293031323334353637383940414243 | |
check_api_key¶
check_api_key(api_key)Source code infastapi/security/api_key.py
454647484950 | |
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 withthe API key and integrates that into the OpenAPI documentation. It extractsthe key value sent in the header automatically and provides it as the dependencyresult. 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 inDepends().
The dependency result will be a string containing the key value.
Example¶
fromfastapiimportDepends,FastAPIfromfastapi.securityimportAPIKeyHeaderapp=FastAPI()header_scheme=APIKeyHeader(name="x-key")@app.get("/items/")asyncdefread_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 beprovided in one of multiple optional ways (for example, in a header orin an HTTP Bearer token). TYPE: |
Source code infastapi/security/api_key.py
177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226 | |
scheme_nameinstance-attribute¶
scheme_name=scheme_nameor__name__auto_errorinstance-attribute¶
auto_error=auto_errormake_not_authenticated_error¶
make_not_authenticated_error()The WWW-Authenticate header is not standardized for API Key authentication butthe HTTP specification requires that an error of 401 "Unauthorized" mustinclude a WWW-Authenticate header.
Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized
For this, this method sends a custom challengeAPIKey.
Source code infastapi/security/api_key.py
293031323334353637383940414243 | |
check_api_key¶
check_api_key(api_key)Source code infastapi/security/api_key.py
454647484950 | |
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 requestwith the API key and integrates that into the OpenAPI documentation. It extractsthe key value sent in the query parameter automatically and provides it as thedependency 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 inDepends().
The dependency result will be a string containing the key value.
Example¶
fromfastapiimportDepends,FastAPIfromfastapi.securityimportAPIKeyQueryapp=FastAPI()query_scheme=APIKeyQuery(name="api_key")@app.get("/items/")asyncdefread_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 beprovided in one of multiple optional ways (for example, in a queryparameter or in an HTTP Bearer token). TYPE: |
Source code infastapi/security/api_key.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138 | |
scheme_nameinstance-attribute¶
scheme_name=scheme_nameor__name__auto_errorinstance-attribute¶
auto_error=auto_errormake_not_authenticated_error¶
make_not_authenticated_error()The WWW-Authenticate header is not standardized for API Key authentication butthe HTTP specification requires that an error of 401 "Unauthorized" mustinclude a WWW-Authenticate header.
Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized
For this, this method sends a custom challengeAPIKey.
Source code infastapi/security/api_key.py
293031323334353637383940414243 | |
check_api_key¶
check_api_key(api_key)Source code infastapi/security/api_key.py
454647484950 | |
HTTP Authentication Schemes¶
fastapi.security.HTTPBasic¶
HTTPBasic(*,scheme_name=None,realm=None,description=None,auto_error=True) Bases:HTTPBase
HTTP Basic authentication.
Ref: https://datatracker.ietf.org/doc/html/rfc7617
Usage¶
Create an instance object and use that object as the dependency inDepends().
The dependency result will be anHTTPBasicCredentials object containing theusername and thepassword.
Read more about it in theFastAPI docs for HTTP Basic Auth.
Example¶
fromtypingimportAnnotatedfromfastapiimportDepends,FastAPIfromfastapi.securityimportHTTPBasic,HTTPBasicCredentialsapp=FastAPI()security=HTTPBasic()@app.get("/users/me")defread_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 (aheader), If This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can beprovided in one of multiple optional ways (for example, in HTTP Basicauthentication or in an HTTP Bearer token). TYPE: |
Source code infastapi/security/http.py
140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195 | |
scheme_nameinstance-attribute¶
scheme_name=scheme_nameor__name__realminstance-attribute¶
realm=realmauto_errorinstance-attribute¶
auto_error=auto_errormake_not_authenticated_error¶
make_not_authenticated_error()Source code infastapi/security/http.py
878889909192 | |
make_authenticate_headers¶
make_authenticate_headers()Source code infastapi/security/http.py
197198199200 | |
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 inDepends().
The dependency result will be anHTTPAuthorizationCredentials object containingthescheme and thecredentials.
Example¶
fromtypingimportAnnotatedfromfastapiimportDepends,FastAPIfromfastapi.securityimportHTTPAuthorizationCredentials,HTTPBearerapp=FastAPI()security=HTTPBearer()@app.get("/users/me")defread_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 is 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 beprovided in one of multiple optional ways (for example, in an HTTPBearer token or in a cookie). TYPE: |
Source code infastapi/security/http.py
254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301 | |
modelinstance-attribute¶
model=HTTPBearer(bearerFormat=bearerFormat,description=description)scheme_nameinstance-attribute¶
scheme_name=scheme_nameor__name__auto_errorinstance-attribute¶
auto_error=auto_errormake_authenticate_headers¶
make_authenticate_headers()Source code infastapi/security/http.py
8485 | |
make_not_authenticated_error¶
make_not_authenticated_error()Source code infastapi/security/http.py
878889909192 | |
fastapi.security.HTTPDigest¶
HTTPDigest(*,scheme_name=None,description=None,auto_error=True) Bases:HTTPBase
HTTP Digest authentication.
Warning: this is only a stub to connect the components with OpenAPI in FastAPI,but it doesn't implement the full Digest scheme, you would need to to subclass itand implement it in your code.
Ref: https://datatracker.ietf.org/doc/html/rfc7616
Usage¶
Create an instance object and use that object as the dependency inDepends().
The dependency result will be anHTTPAuthorizationCredentials object containingthescheme and thecredentials.
Example¶
fromtypingimportAnnotatedfromfastapiimportDepends,FastAPIfromfastapi.securityimportHTTPAuthorizationCredentials,HTTPDigestapp=FastAPI()security=HTTPDigest()@app.get("/users/me")defread_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 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 beprovided in one of multiple optional ways (for example, in HTTPDigest or in a cookie). TYPE: |
Source code infastapi/security/http.py
357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402 | |
scheme_nameinstance-attribute¶
scheme_name=scheme_nameor__name__auto_errorinstance-attribute¶
auto_error=auto_errormake_authenticate_headers¶
make_authenticate_headers()Source code infastapi/security/http.py
8485 | |
make_not_authenticated_error¶
make_not_authenticated_error()Source code infastapi/security/http.py
878889909192 | |
HTTP Credentials¶
fastapi.security.HTTPAuthorizationCredentials¶
Bases:BaseModel
The HTTP authorization credentials in the result of usingHTTPBearer orHTTPDigest in a dependency.
The HTTP authorization header value is split by the first space.
The first part is thescheme, the second part is thecredentials.
For example, in an HTTP Bearer token scheme, the client will send a headerlike:
Authorization: Bearer deadbeef12346In this case:
schemewill have the value"Bearer"credentialswill have the value"deadbeef12346"
fastapi.security.HTTPBasicCredentials¶
Bases:BaseModel
The HTTP Basic credentials given as the result of usingHTTPBasic in adependency.
Read more about it in theFastAPI docs for HTTP Basic Auth.
OAuth2 Authentication¶
fastapi.security.OAuth2¶
OAuth2(*,flows=OAuthFlows(),scheme_name=None,description=None,auto_error=True) Bases:SecurityBase
This is the base class for OAuth2 authentication, an instance of it would be usedas a dependency. All other OAuth2 classes inherit from it and customize it foreach OAuth2 flow.
You normally would not create a new class inheriting from it but use one of theexisting subclasses, and maybe compose them if you want to support multiple flows.
Read more about it in theFastAPI 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 Authorization header is provided, required forOAuth2 authentication, it will automatically cancel the request andsend 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 beprovided in one of multiple optional ways (for example, with OAuth2or in a cookie). TYPE: |
Source code infastapi/security/oauth2.py
343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399 | |
modelinstance-attribute¶
model=OAuth2(flows=cast(OAuthFlows,flows),description=description)scheme_nameinstance-attribute¶
scheme_name=scheme_nameor__name__auto_errorinstance-attribute¶
auto_error=auto_errormake_not_authenticated_error¶
make_not_authenticated_error()The OAuth 2 specification doesn't define the challenge that should be used,because aBearer token is not really the only option to authenticate.
But declaring any other authentication challenge would be application-specificas it's not defined in the specification.
For practical reasons, this method uses theBearer challenge by default, asit's probably the most common one.
If you are implementing an OAuth2 authentication scheme other than the providedones in FastAPI (based on bearer tokens), you might want to override this.
Ref: https://datatracker.ietf.org/doc/html/rfc6749
Source code infastapi/security/oauth2.py
401402403404405406407408409410411412413414415416417418419420421 | |
fastapi.security.OAuth2AuthorizationCodeBearer¶
OAuth2AuthorizationCodeBearer(authorizationUrl,tokenUrl,refreshUrl=None,scheme_name=None,scopes=None,description=None,auto_error=True,) Bases:OAuth2
OAuth2 flow for authentication using a bearer token obtained with an OAuth2 codeflow. An instance of it would be used as a dependency.
| PARAMETER | DESCRIPTION |
|---|---|
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 thepath operations thatuse 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 Authorization header is provided, required forOAuth2 authentication, it will automatically cancel the request andsend 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 beprovided in one of multiple optional ways (for example, with OAuth2or in a cookie). TYPE: |
Source code infastapi/security/oauth2.py
553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640 | |
modelinstance-attribute¶
model=OAuth2(flows=cast(OAuthFlows,flows),description=description)scheme_nameinstance-attribute¶
scheme_name=scheme_nameor__name__auto_errorinstance-attribute¶
auto_error=auto_errormake_not_authenticated_error¶
make_not_authenticated_error()The OAuth 2 specification doesn't define the challenge that should be used,because aBearer token is not really the only option to authenticate.
But declaring any other authentication challenge would be application-specificas it's not defined in the specification.
For practical reasons, this method uses theBearer challenge by default, asit's probably the most common one.
If you are implementing an OAuth2 authentication scheme other than the providedones in FastAPI (based on bearer tokens), you might want to override this.
Ref: https://datatracker.ietf.org/doc/html/rfc6749
Source code infastapi/security/oauth2.py
401402403404405406407408409410411412413414415416417418419420421 | |
fastapi.security.OAuth2PasswordBearer¶
OAuth2PasswordBearer(tokenUrl,scheme_name=None,scopes=None,description=None,auto_error=True,refreshUrl=None,) Bases: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 theFastAPI docs for Simple OAuth2 with Password and Bearer.
| PARAMETER | DESCRIPTION |
|---|---|
tokenUrl | The URL to obtain the OAuth2 token. This would be thepath operationthat has Read more about it in theFastAPI docs for Simple OAuth2 with Password and Bearer. 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 thepath operations thatuse this dependency. Read more about it in theFastAPI docs for Simple OAuth2 with Password and Bearer. 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 Authorization header is provided, required forOAuth2 authentication, it will automatically cancel the request andsend 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 beprovided in one of multiple optional ways (for example, with OAuth2or in a cookie). TYPE: |
refreshUrl | The URL to refresh the token and obtain a new one. TYPE: |
Source code infastapi/security/oauth2.py
442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534 | |
modelinstance-attribute¶
model=OAuth2(flows=cast(OAuthFlows,flows),description=description)scheme_nameinstance-attribute¶
scheme_name=scheme_nameor__name__auto_errorinstance-attribute¶
auto_error=auto_errormake_not_authenticated_error¶
make_not_authenticated_error()The OAuth 2 specification doesn't define the challenge that should be used,because aBearer token is not really the only option to authenticate.
But declaring any other authentication challenge would be application-specificas it's not defined in the specification.
For practical reasons, this method uses theBearer challenge by default, asit's probably the most common one.
If you are implementing an OAuth2 authentication scheme other than the providedones in FastAPI (based on bearer tokens), you might want to override this.
Ref: https://datatracker.ietf.org/doc/html/rfc6749
Source code infastapi/security/oauth2.py
401402403404405406407408409410411412413414415416417418419420421 | |
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 theusername andpassword as form datafor an OAuth2 password flow.
The OAuth2 specification dictates that for a password flow the data should becollected using form data (instead of JSON) and that it should have the specificfieldsusername andpassword.
All the initialization parameters are extracted from the request.
Read more about it in theFastAPI docs for Simple OAuth2 with Password and Bearer.
Example¶
fromtypingimportAnnotatedfromfastapiimportDepends,FastAPIfromfastapi.securityimportOAuth2PasswordRequestFormapp=FastAPI()@app.post("/login")deflogin(form_data:Annotated[OAuth2PasswordRequestForm,Depends()]):data={}data["scopes"]=[]forscopeinform_data.scopes:data["scopes"].append(scope)ifform_data.client_id:data["client_id"]=form_data.client_idifform_data.client_secret:data["client_secret"]=form_data.client_secretreturndataNote that for OAuth2 the scopeitems:read is a single scope in an opaque string.You could have custom internal logic to separate it by colon characters (:) orsimilar, and get the two partsitems andread. Many applications do that togroup and organize permissions, you could do it as well in your application, justknow 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 andallows not passing it. If you want to enforce it, use instead the Read more about it in theFastAPI docs for Simple OAuth2 with Password and Bearer. TYPE: |
username |
Read more about it in theFastAPI docs for Simple OAuth2 with Password and Bearer. TYPE: |
password |
Read more about it in theFastAPI docs for Simple OAuth2 with Password and Bearer. TYPE: |
scope | A single string with actually several scopes separated by spaces. Eachscope is also a string. For example, a single string with: ```python"items:read items:write users:read profile openid"```` would represent the scopes:
Read more about it in theFastAPI docs for Simple OAuth2 with Password and Bearer. TYPE: |
client_id | If there's a TYPE: |
client_secret | If there's a TYPE: |
Source code infastapi/security/oauth2.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159 | |
fastapi.security.OAuth2PasswordRequestFormStrict¶
OAuth2PasswordRequestFormStrict(grant_type,username,password,scope="",client_id=None,client_secret=None,) Bases:OAuth2PasswordRequestForm
This is a dependency class to collect theusername andpassword as form datafor an OAuth2 password flow.
The OAuth2 specification dictates that for a password flow the data should becollected using form data (instead of JSON) and that it should have the specificfieldsusername andpassword.
All the initialization parameters are extracted from the request.
The only difference betweenOAuth2PasswordRequestFormStrict andOAuth2PasswordRequestForm is thatOAuth2PasswordRequestFormStrict requires theclient to send the form fieldgrant_type with the value"password", whichis required in the OAuth2 specification (it seems that for no particular reason),while forOAuth2PasswordRequestFormgrant_type is optional.
Read more about it in theFastAPI docs for Simple OAuth2 with Password and Bearer.
Example¶
fromtypingimportAnnotatedfromfastapiimportDepends,FastAPIfromfastapi.securityimportOAuth2PasswordRequestFormapp=FastAPI()@app.post("/login")deflogin(form_data:Annotated[OAuth2PasswordRequestFormStrict,Depends()]):data={}data["scopes"]=[]forscopeinform_data.scopes:data["scopes"].append(scope)ifform_data.client_id:data["client_id"]=form_data.client_idifform_data.client_secret:data["client_secret"]=form_data.client_secretreturndataNote that for OAuth2 the scopeitems:read is a single scope in an opaque string.You could have custom internal logic to separate it by colon characters (:) orsimilar, and get the two partsitems andread. Many applications do that togroup and organize permissions, you could do it as well in your application, justknow 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 theOAuth2PasswordRequestForm 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_secretclient_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 bepermissive, use instead the Read more about it in theFastAPI docs for Simple OAuth2 with Password and Bearer. TYPE: |
username |
Read more about it in theFastAPI docs for Simple OAuth2 with Password and Bearer. TYPE: |
password |
Read more about it in theFastAPI docs for Simple OAuth2 with Password and Bearer. TYPE: |
scope | A single string with actually several scopes separated by spaces. Eachscope is also a string. For example, a single string with: ```python"items:read items:write users:read profile openid"```` would represent the scopes:
Read more about it in theFastAPI docs for Simple OAuth2 with Password and Bearer. TYPE: |
client_id | If there's a TYPE: |
client_secret | If there's a TYPE: |
Source code infastapi/security/oauth2.py
226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327 | |
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 toobtain the OAuth2 scopes required by all the dependencies in the same chain.
This way, multiple dependencies can have different scopes, even when used in thesamepath operation. And with this, you can access all the scopes required inall those dependencies in a single place.
Read more about it in theFastAPI docs for OAuth2 scopes.
| PARAMETER | DESCRIPTION |
|---|---|
scopes | This will be filled by FastAPI. TYPE: |
Source code infastapi/security/oauth2.py
666667668669670671672673674675676677678679680681682683684685686687688689690691692693 | |
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 adependency.
Warning: this is only a stub to connect the components with OpenAPI in FastAPI,but it doesn't implement the full OpenIdConnect scheme, for example, it doesn't usethe OpenIDConnect URL. You would need to to subclass it and implement it in yourcode.
| 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 Authorization header is provided, required forOpenID Connect authentication, it will automatically cancel the requestand 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 beprovided in one of multiple optional ways (for example, with OpenIDConnect or in a cookie). TYPE: |
Source code infastapi/security/open_id_connect_url.py
222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 | |
modelinstance-attribute¶
model=OpenIdConnect(openIdConnectUrl=openIdConnectUrl,description=description,)scheme_nameinstance-attribute¶
scheme_name=scheme_nameor__name__auto_errorinstance-attribute¶
auto_error=auto_errormake_not_authenticated_error¶
make_not_authenticated_error()Source code infastapi/security/open_id_connect_url.py
808182838485 | |







