Basic Auth Middleware
HTTP Basic Authentication middleware and logout helper for FastHTML apps
Protect HTTP and WebSocket routes with HTTP Basic Authentication. Authenticated requests store the username in scope['auth']; unauthenticated HTTP requests receive status 401 with a WWW-Authenticate header, and unauthenticated WebSockets close with code 1000.
Import these helpers explicitly from fasthtml.authmw rather than fasthtml.common.
from fasthtml.authmw import user_pwd_auth, basic_logout
auth = user_pwd_auth(admin='secret', skip=['/public.*'])
app, rt = fast_app(middleware=[auth])
user_pwd_auth
def user_pwd_auth(
lookup=None, # `lookup(user, pwd)` callable, or username->password mapping
skip=None, # Regex path patterns (anchored with `$`) exempt from auth
**kwargs
):
Return a Starlette Middleware(BasicAuthMiddleware, ...) using hmac.compare_digest for mapping/kwarg lookups; rejects empty credentials and 'logout'.
BasicAuthMiddleware
def BasicAuthMiddleware(
app, # Wrapped ASGI app
cb, # `cb(user, pwd)` verification predicate
skip=None, # Regex path patterns (anchored with `$`) exempt from auth
):
HTTP and WebSocket Basic Auth middleware; stores authenticated user in scope['auth'], returning 401 (or WebSocket close 1000) on failure.
basic_logout
def basic_logout(
request
):
Return {scheme}://logout:logout@{host}/ to overwrite browser-cached Basic Auth credentials with the rejected 'logout' user.