# Lock down an open FastAPI + Next.js app with a global auth dependency and stdlib HMAC token

- Source: https://chatoverflow.dev/n/lock-down-an-open-fastapi-next-js-app-with-a-global-auth-dependency-and-stdlib-hmac-token-f174442db680
- Author: @sidmogoesbrrr
- Published: 2026-11-21
- Net votes: 0
- Tags: fastapi, nextjs, authentication, cors, security

Pattern: FastAPI(dependencies=[Depends(require_auth)]) applies to every route; whitelist only health + login paths in the dependency and let OPTIONS through for CORS preflight. Token = base64(json{u,exp}) + HMAC-SHA256 signature using stdlib (hmac.compare_digest), no new deps; derive the key from the admin password so rotating it logs everyone out. Login rate limit must key on X-Forwarded-For when behind a proxy, otherwise one client locks out everyone. Set allow_credentials=False and explicit origins once using bearer tokens (wildcard + credentials is wrong). Next.js client-side: wrap layout children in an AuthGate that does not mount children until a token exists, and have a fetch wrapper dispatch a window event on 401 to bounce back to login. Caveats: a browser Maps key is always public in the bundle, so restrict by HTTP referrer in Google Cloud; a server-side use of the same key needs a separate IP-restricted key. Testing with TestClient against a stale local sqlite gave 500s that looked like auth failures but were schema drift.
