todo import from typing when deprecating python 3 9 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 bearerhttps fastapi tiangolo comtutorialsecuritysimpleoauth2 example python from typing import annotated from fastapi import depends fastapi from fastapi security import oauth2passwordrequestform app fastapi app postlogin def loginformdata annotatedoauth2passwordrequestform depends data datascopes for scope in formdata scopes datascopes appendscope if formdata clientid dataclientid formdata clientid if formdata clientsecret dataclientsecret formdata clientsecret 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 nevertheless this dependency class is permissive and allows not passing it if you want to enforce it use instead the oauth2passwordrequestformstrict dependency username string the oauth2 spec requires the exact field name username password string the oauth2 spec requires the exact field name password 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 items read items write users read profile openid if there s a clientid it can be sent as part of the form fields but the oauth2 specification recommends sending the clientid and clientsecret if any using http basic auth if there s a clientpassword and a clientid they can be sent as part of the form fields but the oauth2 specification recommends sending the clientid and clientsecret if any using http basic auth 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 granttype with the value password which is required in the oauth2 specification it seems that for no particular reason while for oauth2passwordrequestform granttype is optional read more about it in the fastapi docs for simple oauth2 with password and bearerhttps fastapi tiangolo comtutorialsecuritysimpleoauth2 example python from typing import annotated from fastapi import depends fastapi from fastapi security import oauth2passwordrequestform app fastapi app postlogin def loginformdata annotatedoauth2passwordrequestformstrict depends data datascopes for scope in formdata scopes datascopes appendscope if formdata clientid dataclientid formdata clientid if formdata clientsecret dataclientsecret formdata clientsecret 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 granttype 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 clientid optional string oauth2 recommends sending the clientid and clientsecret if any using http basic auth as clientid clientsecret clientsecret optional string oauth2 recommends sending the clientid and clientsecret if any using http basic auth as clientid clientsecret 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 string the oauth2 spec requires the exact field name username password string the oauth2 spec requires the exact field name password 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 items read items write users read profile openid if there s a clientid it can be sent as part of the form fields but the oauth2 specification recommends sending the clientid and clientsecret if any using http basic auth if there s a clientpassword and a clientid they can be sent as part of the form fields but the oauth2 specification recommends sending the clientid and clientsecret if any using http basic auth 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 securityhttps fastapi tiangolo comtutorialsecurity the dictionary of oauth2 flows security scheme name it will be included in the generated openapi e g visible at docs security scheme description it will be included in the generated openapi e g visible at docs 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 autoerror is set to false when the http ization 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 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 bearerhttps fastapi tiangolo comtutorialsecuritysimpleoauth2 the url to obtain the oauth2 token this would be the path operation that has oauth2passwordrequestform as a dependency security scheme name it will be included in the generated openapi e g visible at docs the oauth2 scopes that would be required by the path operations that use this dependency security scheme description it will be included in the generated openapi e g visible at docs 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 autoerror is set to false when the http ization 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 oauth2 flow for authentication using a bearer token obtained with an oauth2 code flow an instance of it would be used as a dependency the url to obtain the oauth2 token the url to refresh the token and obtain a new one security scheme name it will be included in the generated openapi e g visible at docs the oauth2 scopes that would be required by the path operations that use this dependency security scheme description it will be included in the generated openapi e g visible at docs 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 autoerror is set to false when the http ization 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 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 scopeshttps fastapi tiangolo comadvancedsecurityoauth2scopes this will be filled by fastapi the list of all the scopes required by dependencies all the scopes required by all the dependencies in a single string separated by spaces as defined in the oauth2 specification todo import from typing when deprecating python 3 9 type ignore attr defined 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 https fastapi tiangolo com tutorial security simple oauth2 example python 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 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 string the oauth2 spec requires the exact field name username password string the oauth2 spec requires the exact field name password 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 items read items write users read profile openid 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 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 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 https fastapi tiangolo com tutorial security simple oauth2 example python 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 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 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 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 string the oauth2 spec requires the exact field name username password string the oauth2 spec requires the exact field name password 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 items read items write users read profile openid 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 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 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 https fastapi tiangolo com tutorial security the dictionary of oauth2 flows security scheme name it will be included in the generated openapi e g visible at docs security scheme description it will be included in the generated openapi e g visible at docs 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 auto_error is set to false when the http ization 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 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 https fastapi tiangolo com tutorial security simple oauth2 the url to obtain the oauth2 token this would be the path operation that has oauth2passwordrequestform as a dependency security scheme name it will be included in the generated openapi e g visible at docs the oauth2 scopes that would be required by the path operations that use this dependency security scheme description it will be included in the generated openapi e g visible at docs 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 auto_error is set to false when the http ization 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 oauth2 flow for authentication using a bearer token obtained with an oauth2 code flow an instance of it would be used as a dependency the url to obtain the oauth2 token the url to refresh the token and obtain a new one security scheme name it will be included in the generated openapi e g visible at docs the oauth2 scopes that would be required by the path operations that use this dependency security scheme description it will be included in the generated openapi e g visible at docs 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 auto_error is set to false when the http ization 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 pragma nocover 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 https fastapi tiangolo com advanced security oauth2 scopes this will be filled by fastapi the list of all the scopes required by dependencies all the scopes required by all the dependencies in a single string separated by spaces as defined in the oauth2 specification
from typing import Any, Dict, List, Optional, Union, cast

from fastapi.exceptions import HTTPException
from fastapi.openapi.models import OAuth2 as OAuth2Model
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
from fastapi.param_functions import Form
from fastapi.security.base import SecurityBase
from fastapi.security.utils import get_authorization_scheme_param
from starlette.requests import Request
from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN


from typing_extensions import Annotated, Doc  


class OAuth2PasswordRequestForm:
    

    def __init__(
        self,
        *,
        grant_type: Annotated[
            Union[str, None],
            Form(pattern="password"),
            Doc(
                
            ),
        ] = None,
        username: Annotated[
            str,
            Form(),
            Doc(
                
            ),
        ],
        password: Annotated[
            str,
            Form(),
            Doc(
                
            ),
        ],
        scope: Annotated[
            str,
            Form(),
            Doc(
                
            ),
        ] = "",
        client_id: Annotated[
            Union[str, None],
            Form(),
            Doc(
                
            ),
        ] = None,
        client_secret: Annotated[
            Union[str, None],
            Form(),
            Doc(
                
            ),
        ] = None,
    ):
        self.grant_type = grant_type
        self.username = username
        self.password = password
        self.scopes = scope.split()
        self.client_id = client_id
        self.client_secret = client_secret


class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm):
    

    def __init__(
        self,
        grant_type: Annotated[
            str,
            Form(pattern="password"),
            Doc(
                
            ),
        ],
        username: Annotated[
            str,
            Form(),
            Doc(
                
            ),
        ],
        password: Annotated[
            str,
            Form(),
            Doc(
                
            ),
        ],
        scope: Annotated[
            str,
            Form(),
            Doc(
                
            ),
        ] = "",
        client_id: Annotated[
            Union[str, None],
            Form(),
            Doc(
                
            ),
        ] = None,
        client_secret: Annotated[
            Union[str, None],
            Form(),
            Doc(
                
            ),
        ] = None,
    ):
        super().__init__(
            grant_type=grant_type,
            username=username,
            password=password,
            scope=scope,
            client_id=client_id,
            client_secret=client_secret,
        )


class OAuth2(SecurityBase):
    

    def __init__(
        self,
        *,
        flows: Annotated[
            Union[OAuthFlowsModel, Dict[str, Dict[str, Any]]],
            Doc(
                
            ),
        ] = OAuthFlowsModel(),
        scheme_name: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        description: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        auto_error: Annotated[
            bool,
            Doc(
                
            ),
        ] = True,
    ):
        self.model = OAuth2Model(
            flows=cast(OAuthFlowsModel, flows), description=description
        )
        self.scheme_name = scheme_name or self.__class__.__name__
        self.auto_error = auto_error

    async def __call__(self, request: Request) -> Optional[str]:
        authorization = request.headers.get("Authorization")
        if not authorization:
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
                )
            else:
                return None
        return authorization


class OAuth2PasswordBearer(OAuth2):
    

    def __init__(
        self,
        tokenUrl: Annotated[
            str,
            Doc(
                
            ),
        ],
        scheme_name: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        scopes: Annotated[
            Optional[Dict[str, str]],
            Doc(
                
            ),
        ] = None,
        description: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        auto_error: Annotated[
            bool,
            Doc(
                
            ),
        ] = True,
    ):
        if not scopes:
            scopes = {}
        flows = OAuthFlowsModel(
            password=cast(Any, {"tokenUrl": tokenUrl, "scopes": scopes})
        )
        super().__init__(
            flows=flows,
            scheme_name=scheme_name,
            description=description,
            auto_error=auto_error,
        )

    async def __call__(self, request: Request) -> Optional[str]:
        authorization = request.headers.get("Authorization")
        scheme, param = get_authorization_scheme_param(authorization)
        if not authorization or scheme.lower() != "bearer":
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_401_UNAUTHORIZED,
                    detail="Not authenticated",
                    headers={"WWW-Authenticate": "Bearer"},
                )
            else:
                return None
        return param


class OAuth2AuthorizationCodeBearer(OAuth2):
    

    def __init__(
        self,
        authorizationUrl: str,
        tokenUrl: Annotated[
            str,
            Doc(
                
            ),
        ],
        refreshUrl: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        scheme_name: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        scopes: Annotated[
            Optional[Dict[str, str]],
            Doc(
                
            ),
        ] = None,
        description: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        auto_error: Annotated[
            bool,
            Doc(
                
            ),
        ] = True,
    ):
        if not scopes:
            scopes = {}
        flows = OAuthFlowsModel(
            authorizationCode=cast(
                Any,
                {
                    "authorizationUrl": authorizationUrl,
                    "tokenUrl": tokenUrl,
                    "refreshUrl": refreshUrl,
                    "scopes": scopes,
                },
            )
        )
        super().__init__(
            flows=flows,
            scheme_name=scheme_name,
            description=description,
            auto_error=auto_error,
        )

    async def __call__(self, request: Request) -> Optional[str]:
        authorization = request.headers.get("Authorization")
        scheme, param = get_authorization_scheme_param(authorization)
        if not authorization or scheme.lower() != "bearer":
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_401_UNAUTHORIZED,
                    detail="Not authenticated",
                    headers={"WWW-Authenticate": "Bearer"},
                )
            else:
                return None  
        return param


class SecurityScopes:
    

    def __init__(
        self,
        scopes: Annotated[
            Optional[List[str]],
            Doc(
                
            ),
        ] = None,
    ):
        self.scopes: Annotated[
            List[str],
            Doc(
                
            ),
        ] = scopes or []
        self.scope_str: Annotated[
            str,
            Doc(
                
            ),
        ] = " ".join(self.scopes)