Skip to main content

OAuth2PasswordBearer

OAuth2 flow for authentication using a bearer token obtained with a password. An instance of it would be used as a dependency.

Parameters

tokenUrl
str
required
The URL to obtain the OAuth2 token. This would be the path operation that has OAuth2PasswordRequestForm as a dependency.
scheme_name
str | None
default:"None"
Security scheme name. It will be included in the generated OpenAPI (e.g. visible at /docs).
scopes
dict[str, str] | None
default:"None"
The OAuth2 scopes that would be required by the path operations that use this dependency.
description
str | None
default:"None"
Security scheme description. It will be included in the generated OpenAPI (e.g. visible at /docs).
auto_error
bool
default:"True"
By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error.If auto_error is set to False, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be None.This is useful when you want to have optional authentication or when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie).
refreshUrl
str | None
default:"None"
The URL to refresh the token and obtain a new one.

Example

from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/items/")
async def read_items(token: Annotated[str, Depends(oauth2_scheme)]):
    return {"token": token}

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.

Parameters

grant_type
str | None
default:"None"
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 OAuth2PasswordRequestFormStrict dependency.
username
str
required
username string. The OAuth2 spec requires the exact field name username.
password
str
required
password string. The OAuth2 spec requires the exact field name password.
scope
str
default:""
A single string with actually several scopes separated by spaces. Each scope is also a string.For example, a single string with:
"items:read items:write users:read profile openid"
would represent the scopes:
  • items:read
  • items:write
  • users:read
  • profile
  • openid
client_id
str | None
default:"None"
If there’s a client_id, it can be sent as part of the form fields. But the OAuth2 specification recommends sending the client_id and client_secret (if any) using HTTP Basic auth.
client_secret
str | None
default:"None"
If there’s a client_password (and a client_id), they can be sent as part of the form fields. But the OAuth2 specification recommends sending the client_id and client_secret (if any) using HTTP Basic auth.

Attributes

After initialization, the form will have these attributes:
  • grant_type: The grant type value
  • username: The username value
  • password: The password value
  • scopes: A list of scope strings (parsed from the scope parameter)
  • client_id: The client ID value
  • client_secret: The client secret value

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

OAuth2PasswordRequestFormStrict

This is a dependency class to collect the username and password as form data for an OAuth2 password flow. 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, while for OAuth2PasswordRequestForm grant_type is optional.

Parameters

grant_type
str
required
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
str
required
username string. The OAuth2 spec requires the exact field name username.
password
str
required
password string. The OAuth2 spec requires the exact field name password.
scope
str
default:""
A single string with actually several scopes separated by spaces.
client_id
str | None
default:"None"
If there’s a client_id, it can be sent as part of the form fields. But the OAuth2 specification recommends sending the client_id and client_secret (if any) using HTTP Basic auth.
client_secret
str | None
default:"None"
If there’s a client_password (and a client_id), they can be sent as part of the form fields. But the OAuth2 specification recommends sending the client_id and client_secret (if any) using HTTP Basic auth.

OAuth2AuthorizationCodeBearer

OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code flow. An instance of it would be used as a dependency.

Parameters

authorizationUrl
str
required
The URL for OAuth2 authorization.
tokenUrl
str
required
The URL to obtain the OAuth2 token.
refreshUrl
str | None
default:"None"
The URL to refresh the token and obtain a new one.
scheme_name
str | None
default:"None"
Security scheme name. It will be included in the generated OpenAPI (e.g. visible at /docs).
scopes
dict[str, str] | None
default:"None"
The OAuth2 scopes that would be required by the path operations that use this dependency.
description
str | None
default:"None"
Security scheme description. It will be included in the generated OpenAPI (e.g. visible at /docs).
auto_error
bool
default:"True"
By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error.If auto_error is set to False, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be None.This is useful when you want to have optional authentication or when authentication can be provided in one of multiple optional ways.

Example

from fastapi import FastAPI, Depends
from fastapi.security import OAuth2AuthorizationCodeBearer

app = FastAPI()

oauth2_scheme = OAuth2AuthorizationCodeBearer(
    authorizationUrl="https://example.com/oauth/authorize",
    tokenUrl="https://example.com/oauth/token"
)

@app.get("/items/")
async def read_items(token: str = Depends(oauth2_scheme)):
    return {"token": token}

SecurityScopes

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.

Parameters

scopes
list[str] | None
default:"None"
This will be filled by FastAPI.

Attributes

scopes
list[str]
The list of all the scopes required by dependencies.
scope_str
str
All the scopes required by all the dependencies in a single string separated by spaces, as defined in the OAuth2 specification.

Build docs developers (and LLMs) love