Skip to main content

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

AttributeTypeDescription
modelOAuth2ModelThe OAuth2Model instance containing the OAuth2 flows and description for the security scheme.
scheme_name`strNone`
auto_errorboolA boolean indicating whether to automatically cancel the request and send an error if no HTTP Authorization header is provided, or if set to False, the dependency result will be None for optional authentication.

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
) - > null

Parameters

NameTypeDescription
flows`OAuthFlowsModeldict[str, dict[str, Any]]` = OAuthFlowsModel()
scheme_name`strNone` = None
description`strNone` = None
auto_errorbool = TrueBy 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. 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).

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. Ref: https://datatracker.ietf.org/doc/html/rfc6749

Returns

TypeDescription
[HTTPException](../../exceptions/httpexception.md?sid=fastapi_exceptions_httpexception)