Describe Problem
The application requires secure authentication for the SPA frontend to communicate with the FastAPI backend API. Direct OAuth2 flows from the browser (implicit flow or authorization code with PKCE stored in browser) expose tokens to XSS attacks and require complex token management in the frontend. Without a Backend-for-Frontend (BFF) pattern, the frontend must handle token refresh, storage, and secure transmission, increasing attack surface and complexity.
Suggest Solution
Implement a BFF OAuth2 proxy using oauth2-proxy with the following architecture:
- Deploy oauth2-proxy as an intermediary between the SPA and backend API
- Configure OIDC authentication with Microsoft Entra ID (Azure AD)
- Use PKCE (
code_challenge_method: S256) for secure authorization code flow
- Enable Redis-backed session storage for horizontal scalability
- Configure Nginx reverse proxy with
auth_request directive
- Route
/oauth2/* paths directly to oauth2-proxy
- Enforce authentication on
/api/* routes (return 401 if unauthenticated)
- Redirect unauthenticated users to sign-in for all other routes
- Token injection via headers
- Inject
Authorization: Bearer <id_token> header for API requests
- Forward
X-Auth-Request-Access-Token for additional validation
- Secure cookie configuration
cookie_secure: true, cookie_httponly: true, cookie_samesite: lax
- 15-minute token refresh interval, 1-hour session expiry
- CSRF protection with per-request tokens
- Backend JWT validation in FastAPI
- Validate tokens against Azure AD JWKS endpoint
- Extract user claims (oid, name, email, roles) for authorization
Additional Details
Describe Problem
The application requires secure authentication for the SPA frontend to communicate with the FastAPI backend API. Direct OAuth2 flows from the browser (implicit flow or authorization code with PKCE stored in browser) expose tokens to XSS attacks and require complex token management in the frontend. Without a Backend-for-Frontend (BFF) pattern, the frontend must handle token refresh, storage, and secure transmission, increasing attack surface and complexity.
Suggest Solution
Implement a BFF OAuth2 proxy using oauth2-proxy with the following architecture:
code_challenge_method: S256) for secure authorization code flowauth_requestdirective/oauth2/*paths directly to oauth2-proxy/api/*routes (return 401 if unauthenticated)Authorization: Bearer <id_token>header for API requestsX-Auth-Request-Access-Tokenfor additional validationcookie_secure: true,cookie_httponly: true,cookie_samesite: laxAdditional Details