Skip to content

Instantly share code, notes, and snippets.

@Dmitri-Sintsov
Last active January 15, 2025 09:42
Show Gist options
  • Save Dmitri-Sintsov/809cc887605d81088382982e224c6bea to your computer and use it in GitHub Desktop.
Save Dmitri-Sintsov/809cc887605d81088382982e224c6bea to your computer and use it in GitHub Desktop.
sqladmin http basic authentication
import base64
import binascii
import secrets
from starlette.authentication import (
AuthCredentials, AuthenticationBackend, AuthenticationError, SimpleUser
)
from starlette.requests import HTTPConnection
from starlette.responses import Response, JSONResponse
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
class BasicAuthMiddleware(AuthenticationMiddleware):
def default_on_error(self, conn: HTTPConnection, exc: Exception) -> Response:
if isinstance(exc, AuthenticationError):
return JSONResponse(
status_code=401,
content={"message": "Basic authentication"},
headers={"WWW-Authenticate": "Basic"}
)
else:
return super().default_on_error(conn, exc)
class BasicAuthBackend(AuthenticationBackend):
admin_username = 'admin'
admin_password = 'admin'
async def authenticate(self, conn):
if "Authorization" not in conn.headers:
raise AuthenticationError('Invalid basic auth credentials')
auth = conn.headers["Authorization"]
try:
scheme, credentials = auth.split()
if scheme.lower() != 'basic':
raise AuthenticationError('Invalid basic auth credentials')
decoded = base64.b64decode(credentials).decode("ascii")
except (ValueError, UnicodeDecodeError, binascii.Error) as exc:
raise AuthenticationError('Invalid basic auth credentials')
username, _, password = decoded.partition(":")
if not (secrets.compare_digest(username, self.admin_username) and secrets.compare_digest(password, self.admin_password)):
raise AuthenticationError('Invalid basic auth credentials')
return AuthCredentials(["authenticated"]), SimpleUser(username)
admin_middlewares = [
Middleware(BasicAuthMiddleware, backend=BasicAuthBackend())
]
from fastapi import FastAPI
from sqladmin import Admin
from .config.database import engine
from .config.admin import admin_middlewares
app = FastAPI()
admin = Admin(app=app, engine=engine, middlewares=admin_middlewares)
# admin.add_view(MyModelAdmin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment