OAuth2
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.
Attributes
| Attribute | Type | Description |
|---|---|---|
| model | OAuth2Model | An OAuth2Model instance containing the dictionary of OAuth2 flows and the security scheme description used for OpenAPI generation. |
| scheme_name | string | Security scheme name that will be included in the generated OpenAPI (e.g. visible at /docs). |
| auto_error | boolean = True | If set to False, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be None. |
Constructor
Signature
def OAuth2(
flows: OAuthFlowsModel | dict[str, dict[str, Any]] = OAuthFlowsModel(),
scheme_name: str | None = None,
description: str | None = None,
auto_error: bool = True
)
Parameters
| Name | Type | Description |
|---|---|---|
| flows | `OAuthFlowsModel | dict[str, dict[str, Any]]` = OAuthFlowsModel() |
| scheme_name | `str | None` = None |
| description | `str | None` = None |
| auto_error | bool = True | If True, missing credentials trigger an automatic HTTP error; if False, the dependency returns None. |
Signature
def OAuth2(
flows: OAuthFlowsModel | dict[str, dict[str, Any]] = OAuthFlowsModel(),
scheme_name: str | None = None,
description: str | None = None,
auto_error: bool = True
)
Parameters
| Name | Type | Description |
|---|---|---|
| flows | `OAuthFlowsModel | dict[str, dict[str, Any]]` = OAuthFlowsModel() |
| scheme_name | `str | None` = None |
| description | `str | None` = None |
| auto_error | bool = True | Determines if the dependency should raise an HTTPException when the Authorization header is missing; if False, it returns None instead. |
Methods
make_not_authenticated_error()
@classmethod
def make_not_authenticated_error() - > [HTTPException](../../exceptions/httpexception.md?sid=fastapi_exceptions_httpexception)
The OAuth 2 specification doesn't define the challenge that should be used, because a Bearer token is not really the only option to authenticate. But declaring any other authentication challenge would be application-specific as it's not defined in the specification. For practical reasons, this method uses the Bearer challenge by default, as it's probably the most common one. If you are implementing an OAuth2 authentication scheme other than the provided ones in FastAPI (based on bearer tokens), you might want to override this.
Returns
| Type | Description |
|---|---|
[HTTPException](../../exceptions/httpexception.md?sid=fastapi_exceptions_httpexception) | An HTTP 401 Unauthorized exception containing a WWW-Authenticate: Bearer header. |