import base64 import binascii from starlette.authentication import AuthenticationBackend, AuthenticationError class BasicAuthBackend(AuthenticationBackend): async def authenticate(self, conn): if "Authorization" not in conn.headers: raise AuthenticationError('No Authorization Header') auth = conn.headers["Authorization"] try: scheme, creds = auth.split() if scheme.lower() != "basic": raise AuthenticationError('Invalid Auth Scheme') decoded = base64.b64decode(creds).decode("utf-8") except (ValueError, UnicodeDecodeError, binascii.Error): raise AuthenticationError('Invalid basic auth credentials') username, _, password = decoded.partition(":") if username == 'admin' and password == 'password': return None raise AuthenticationError('Invalid basic auth credentials')