Monarch API Authentication
This document describes the authentication system for the Monarch API.
Overview
The authentication system provides:
- Authentication required by default for all endpoints via a global dependency
- Ability to opt out per-endpoint using
@allow_anonymous - Automatic bypass for internal Docker network requests
- OAuth2 Authorization Code Flow with PKCE for browser/Swagger UI authentication
- Client credentials flow for service-to-service authentication
- Configurable Swagger documentation (dev vs release modes)
How It Works
Request Flow
- Internal requests (no
X-Forwarded-Forheader) → Auth always bypassed - External requests (with
X-Forwarded-Forheader) → Auth enforced globally unless endpoint is marked@allow_anonymous - Token validation via Keycloak JWT decode (checks signature & expiry)
Authentication Sources
Authorization: Bearer <token>headerapi_authcookie (for browser sessions)
Environment Variables
Set by the setup-sso.sh script:
API_KEYCLOAK_CLIENT_ID=
API_KEYCLOAK_CLIENT_SECRET=
API_AUTH_REDIRECT_URI=
SWAGGER_MODE=dev # or 'release' for production
Using Authentication
Protected Endpoint
Endpoints are protected by default; no change needed.
Public Endpoint
from monarch_api.auth.decorators import public_doc, allow_anonymous
@router.get("/health")
@public_doc # Shows in Swagger when SWAGGER_MODE=release
@allow_anonymous # Opt-out of auth
async def health_check():
return {"status": "ok"}
Note: Endpoints are protected by default. Use @allow_anonymous to opt out when needed.
Authentication Endpoints
/auth/login- Initiates OAuth2 flow with PKCE/auth/callback- Handles OAuth2 callback, sets cookie/auth/token- Client credentials for service-to-service auth
Swagger UI Integration
The Swagger UI at /docs includes:
- "Authorize" button for OAuth2 authentication
- PKCE support for secure browser-based auth
- Pre-configured client ID
Swagger Modes
- Dev Mode (
SWAGGER_MODE=dev) - All endpoints visible - Release Mode (
SWAGGER_MODE=release) - Only@public_docendpoints visible
Security Features
- PKCE prevents authorization code interception
- State parameter prevents CSRF attacks
- Secure cookies (HttpOnly, Secure, SameSite=Lax)
- Redis-based state storage (10-minute expiry)
- Internal network bypass via proxy headers
Internal Service Requests
Internal requests from within the Docker network automatically bypass authentication. The system identifies internal requests by the absence of the X-Forwarded-For header.