56 lines
2.2 KiB
Markdown
56 lines
2.2 KiB
Markdown
# 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
|
|
|
|
1. **Unauthenticated Request** → User visits `/` without a session
|
|
2. **Redirect to Login** → Dashboard redirects to `/login`
|
|
3. **OAuth Flow** → `/login` initiates Azure Entra ID authorization
|
|
4. **Callback** → After user approves, Entra redirects to `/auth/callback`
|
|
5. **Session Created** → User info stored in `request.session["user"]`
|
|
6. **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 with `sub`, `name`, `email`
|
|
|
|
## Environment Variables
|
|
|
|
```bash
|
|
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
|
|
|
|
1. Register app in [Azure Portal](https://portal.azure.com) (see [README.md](README.md))
|
|
2. Create `.env` with credentials
|
|
3. Start: `uv run uvicorn app.main:app --reload`
|
|
4. Visit `http://127.0.0.1:8000/` → redirects to `/login`
|
|
5. Click login → completes Entra auth flow → redirects to dashboard
|
|
6. Click logout at `/logout` → clears session, returns to home
|