2.2 KiB
2.2 KiB
OAuth 2.0 Integration with Azure Entra ID
Overview
The dashboard (/) is now protected by Azure Entra ID OAuth authentication. Unauthenticated users are redirected to login.
How It Works
- Unauthenticated Request → User visits
/without a session - Redirect to Login → Dashboard redirects to
/login - OAuth Flow →
/logininitiates Azure Entra ID authorization - Callback → After user approves, Entra redirects to
/auth/callback - Session Created → User info stored in
request.session["user"] - Access Granted → Dashboard renders with authenticated user data
Key Files
| File | Purpose |
|---|---|
app/core/settings.py |
Load OAuth config from .env |
app/core/auth.py |
OAuth client setup (Authlib + Entra metadata) |
app/views/auth.py |
Routes: /login, /auth/callback, /logout |
app/views/dashboard.py |
Protected route; redirects unauthenticated users |
app/core/app_factory.py |
Register SessionMiddleware + routers |
.env |
Runtime secrets (tenant ID, client ID/secret, session key) |
Session & Middleware
- SessionMiddleware: Signs/validates session cookies with
SESSION_SECRET_KEY - Session data: Stored client-side in encrypted cookie (secure, stateless)
- Session keys:
request.session.get("user")contains user object withsub,name,email
Environment Variables
SESSION_SECRET_KEY # 32-byte random secret for session signing
AZURE_TENANT_ID # Azure Entra tenant ID
AZURE_CLIENT_ID # Entra app registration client ID
AZURE_CLIENT_SECRET # Entra app registration client secret
Dependencies Added
- authlib: OAuth 2.0 client for OpenID Connect flows
- httpx: HTTP client for Authlib OAuth requests
- itsdangerous: Session cookie signing
Testing Locally
- Register app in Azure Portal (see README.md)
- Create
.envwith credentials - Start:
uv run uvicorn app.main:app --reload - Visit
http://127.0.0.1:8000/→ redirects to/login - Click login → completes Entra auth flow → redirects to dashboard
- Click logout at
/logout→ clears session, returns to home