the http basic credendials given as the result of using httpbasic in a dependency read more about it in the fastapi docs for http basic authhttps fastapi tiangolo comadvancedsecurityhttpbasicauth the http ization credentials in the result of using httpbearer or httpdigest in a dependency the http ization header value is split by the first space the first part is the scheme the second part is the credentials for example in an http bearer token scheme the client will send a header like ization bearer deadbeef12346 in this case scheme will have the value bearer credentials will have the value deadbeef12346 the http ization scheme extracted from the header value the http ization credentials extracted from the header value http basic authentication usage create an instance object and use that object as the dependency in depends the dependency result will be an httpbasiccredentials object containing the username and the password read more about it in the fastapi docs for http basic authhttps fastapi tiangolo comadvancedsecurityhttpbasicauth example python from typing import annotated from fastapi import depends fastapi from fastapi security import httpbasic httpbasiccredentials app fastapi security httpbasic app getusersme def readcurrentusercredentials annotatedhttpbasiccredentials dependssecurity return username credentials username password credentials password security scheme name it will be included in the generated openapi e g visible at docs http basic authentication realm security scheme description it will be included in the generated openapi e g visible at docs by default if the http basic authentication is not provided a header httpbasic will automatically cancel the request and send the client an error if autoerror is set to false when the http basic authentication 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 in http basic authentication or in an http bearer token http bearer token authentication usage create an instance object and use that object as the dependency in depends the dependency result will be an httpizationcredentials object containing the scheme and the credentials example python from typing import annotated from fastapi import depends fastapi from fastapi security import httpizationcredentials httpbearer app fastapi security httpbearer app getusersme def readcurrentuser credentials annotatedhttpizationcredentials dependssecurity return scheme credentials scheme credentials credentials credentials 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 the http bearer token not provided in an ization header httpbearer will automatically cancel the request and send the client an error if autoerror is set to false when the http bearer token 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 in an http bearer token or in a cookie http digest authentication usage create an instance object and use that object as the dependency in depends the dependency result will be an httpizationcredentials object containing the scheme and the credentials example python from typing import annotated from fastapi import depends fastapi from fastapi security import httpizationcredentials httpdigest app fastapi security httpdigest app getusersme def readcurrentuser credentials annotatedhttpizationcredentials dependssecurity return scheme credentials scheme credentials credentials credentials 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 the http digest not provided httpdigest will automatically cancel the request and send the client an error if autoerror is set to false when the http digest 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 in http digest or in a cookie type ignore attr defined the http basic credendials given as the result of using httpbasic in a dependency read more about it in the fastapi docs for http basic auth https fastapi tiangolo com advanced security http basic auth the http ization credentials in the result of using httpbearer or httpdigest in a dependency the http ization header value is split by the first space the first part is the scheme the second part is the credentials for example in an http bearer token scheme the client will send a header like ization bearer deadbeef12346 in this case scheme will have the value bearer credentials will have the value deadbeef12346 the http ization scheme extracted from the header value the http ization credentials extracted from the header value http basic authentication usage create an instance object and use that object as the dependency in depends the dependency result will be an httpbasiccredentials object containing the username and the password read more about it in the fastapi docs for http basic auth https fastapi tiangolo com advanced security http basic auth example python from typing import annotated from fastapi import depends fastapi from fastapi security import httpbasic httpbasiccredentials app fastapi security httpbasic app get users me def read_current_user credentials annotated httpbasiccredentials depends security return username credentials username password credentials password security scheme name it will be included in the generated openapi e g visible at docs http basic authentication realm security scheme description it will be included in the generated openapi e g visible at docs by default if the http basic authentication is not provided a header httpbasic will automatically cancel the request and send the client an error if auto_error is set to false when the http basic authentication 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 in http basic authentication or in an http bearer token type ignore noqa b904 http bearer token authentication usage create an instance object and use that object as the dependency in depends the dependency result will be an httpizationcredentials object containing the scheme and the credentials example python from typing import annotated from fastapi import depends fastapi from fastapi security import httpizationcredentials httpbearer app fastapi security httpbearer app get users me def read_current_user credentials annotated httpizationcredentials depends security return scheme credentials scheme credentials credentials credentials 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 the http bearer token not provided in an ization header httpbearer will automatically cancel the request and send the client an error if auto_error is set to false when the http bearer token 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 in an http bearer token or in a cookie http digest authentication usage create an instance object and use that object as the dependency in depends the dependency result will be an httpizationcredentials object containing the scheme and the credentials example python from typing import annotated from fastapi import depends fastapi from fastapi security import httpizationcredentials httpdigest app fastapi security httpdigest app get users me def read_current_user credentials annotated httpizationcredentials depends security return scheme credentials scheme credentials credentials credentials 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 the http digest not provided httpdigest will automatically cancel the request and send the client an error if auto_error is set to false when the http digest 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 in http digest or in a cookie
import binascii
from base64 import b64decode
from typing import Optional

from fastapi.exceptions import HTTPException
from fastapi.openapi.models import HTTPBase as HTTPBaseModel
from fastapi.openapi.models import HTTPBearer as HTTPBearerModel
from fastapi.security.base import SecurityBase
from fastapi.security.utils import get_authorization_scheme_param
from pydantic import BaseModel
from starlette.requests import Request
from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
from typing_extensions import Annotated, Doc  


class HTTPBasicCredentials(BaseModel):
    

    username: Annotated[str, Doc("The HTTP Basic username.")]
    password: Annotated[str, Doc("The HTTP Basic password.")]


class HTTPAuthorizationCredentials(BaseModel):
    

    scheme: Annotated[
        str,
        Doc(
            
        ),
    ]
    credentials: Annotated[
        str,
        Doc(
            
        ),
    ]


class HTTPBase(SecurityBase):
    def __init__(
        self,
        *,
        scheme: str,
        scheme_name: Optional[str] = None,
        description: Optional[str] = None,
        auto_error: bool = True,
    ):
        self.model = HTTPBaseModel(scheme=scheme, description=description)
        self.scheme_name = scheme_name or self.__class__.__name__
        self.auto_error = auto_error

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


class HTTPBasic(HTTPBase):
    

    def __init__(
        self,
        *,
        scheme_name: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        realm: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        description: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        auto_error: Annotated[
            bool,
            Doc(
                
            ),
        ] = True,
    ):
        self.model = HTTPBaseModel(scheme="basic", description=description)
        self.scheme_name = scheme_name or self.__class__.__name__
        self.realm = realm
        self.auto_error = auto_error

    async def __call__(  
        self, request: Request
    ) -> Optional[HTTPBasicCredentials]:
        authorization = request.headers.get("Authorization")
        scheme, param = get_authorization_scheme_param(authorization)
        if self.realm:
            unauthorized_headers = {"WWW-Authenticate": f'Basic realm="{self.realm}"'}
        else:
            unauthorized_headers = {"WWW-Authenticate": "Basic"}
        if not authorization or scheme.lower() != "basic":
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_401_UNAUTHORIZED,
                    detail="Not authenticated",
                    headers=unauthorized_headers,
                )
            else:
                return None
        invalid_user_credentials_exc = HTTPException(
            status_code=HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers=unauthorized_headers,
        )
        try:
            data = b64decode(param).decode("ascii")
        except (ValueError, UnicodeDecodeError, binascii.Error):
            raise invalid_user_credentials_exc  
        username, separator, password = data.partition(":")
        if not separator:
            raise invalid_user_credentials_exc
        return HTTPBasicCredentials(username=username, password=password)


class HTTPBearer(HTTPBase):
    

    def __init__(
        self,
        *,
        bearerFormat: Annotated[Optional[str], Doc("Bearer token format.")] = None,
        scheme_name: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        description: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        auto_error: Annotated[
            bool,
            Doc(
                
            ),
        ] = True,
    ):
        self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description)
        self.scheme_name = scheme_name or self.__class__.__name__
        self.auto_error = auto_error

    async def __call__(
        self, request: Request
    ) -> Optional[HTTPAuthorizationCredentials]:
        authorization = request.headers.get("Authorization")
        scheme, credentials = get_authorization_scheme_param(authorization)
        if not (authorization and scheme and credentials):
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
                )
            else:
                return None
        if scheme.lower() != "bearer":
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_403_FORBIDDEN,
                    detail="Invalid authentication credentials",
                )
            else:
                return None
        return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)


class HTTPDigest(HTTPBase):
    

    def __init__(
        self,
        *,
        scheme_name: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        description: Annotated[
            Optional[str],
            Doc(
                
            ),
        ] = None,
        auto_error: Annotated[
            bool,
            Doc(
                
            ),
        ] = True,
    ):
        self.model = HTTPBaseModel(scheme="digest", description=description)
        self.scheme_name = scheme_name or self.__class__.__name__
        self.auto_error = auto_error

    async def __call__(
        self, request: Request
    ) -> Optional[HTTPAuthorizationCredentials]:
        authorization = request.headers.get("Authorization")
        scheme, credentials = get_authorization_scheme_param(authorization)
        if not (authorization and scheme and credentials):
            if self.auto_error:
                raise HTTPException(
                    status_code=HTTP_403_FORBIDDEN, detail="Not authenticated"
                )
            else:
                return None
        if scheme.lower() != "digest":
            raise HTTPException(
                status_code=HTTP_403_FORBIDDEN,
                detail="Invalid authentication credentials",
            )
        return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)