Serve a Password Protected Static Site
NotesThis version of the static site server requires a username and password, which is handy for sharing something privately, such as a draft site or internal documentation. It uses HTTP Basic authentication, which every browser supports with its own login prompt.
import base64
import secrets
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import PlainTextResponse
from fastapi.staticfiles import StaticFiles
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
CONF_MAIN_APP_HOST: str = "0.0.0.0"
CONF_MAIN_APP_PORT: int = 8080
CONF_DEBUG_LEVEL: str = "info"
CONF_SSL_KEYFILE: str | None = None
CONF_SSL_CERTFILE: str | None = None
# Required: the application won't start without them
CONF_SITE_USERNAME: str
CONF_SITE_PASSWORD: str
settings = Settings()
app = FastAPI(
title="FastAPI Static Web Server",
description="A single file Python FastAPI application for serving a password protected static web site.",
version="1.0.0",
openapi_url=None,
)
def is_authorised(request: Request) -> bool:
"""Check the HTTP Basic credentials the browser sends with every request."""
scheme, _, encoded = request.headers.get("authorization", "").partition(" ")
if scheme.lower() != "basic":
return False
try:
username, _, password = base64.b64decode(encoded).decode().partition(":")
except ValueError:
return False
# compare_digest takes the same time however much matches, so timing reveals nothing
return (secrets.compare_digest(username.encode(), settings.CONF_SITE_USERNAME.encode())
& secrets.compare_digest(password.encode(), settings.CONF_SITE_PASSWORD.encode()))
@app.middleware("http")
async def require_password(request: Request, call_next):
if not is_authorised(request):
# Asks the browser to show its username and password prompt
return PlainTextResponse("Unauthorised", status_code=401,
headers={"WWW-Authenticate": 'Basic realm="Private site"'})
return await call_next(request)
app.mount('/', StaticFiles(directory="site", html=True), name="site")
if __name__ == '__main__':
uvicorn.run(app,
host=settings.CONF_MAIN_APP_HOST,
port=settings.CONF_MAIN_APP_PORT,
log_level=settings.CONF_DEBUG_LEVEL,
ssl_keyfile=settings.CONF_SSL_KEYFILE,
ssl_certfile=settings.CONF_SSL_CERTFILE,
proxy_headers=True,
forwarded_allow_ips="*")CONF_SITE_USERNAMEandCONF_SITE_PASSWORDhave no defaults, so the application refuses to start without them: there’s no chance of accidentally running it unprotected.- The middleware checks every request, before the static files are served. (A
Depends()wouldn’t work here, because mounted applications likeStaticFilesdon’t run route dependencies.) - Browsers send the username and password with every request, base64-encoded, in the
Authorizationheader. If they’re missing or wrong, the401response withWWW-Authenticate: Basicmakes the browser show its login prompt. secrets.compare_digestcompares in constant time, so the time taken doesn’t reveal how much of the username or password was right. The&(rather thanand) makes sure both are always compared.
Run it with the username and password in environment variables:
CONF_SITE_USERNAME=admin CONF_SITE_PASSWORD='a long passphrase' python serve_protected.pyBasic authentication sends the password with every request, only encoded, not encrypted. Only ever use it over HTTPS: with CONF_SSL_KEYFILE and CONF_SSL_CERTFILE, or behind a reverse proxy or OpenShift Route that handles TLS.
An earlier draft of this page had several typos that stopped it running, and didn’t yet check a password at all. This version was tested: requests without credentials, or with wrong or malformed ones, get 401, and the right username and password get the site.