The auth dependency was requiring the Authorization header before checking DISABLE_AUTH, causing API endpoints to fail in dev mode. Now returns mock user immediately when DISABLE_AUTH=true. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
61 lines
2 KiB
Python
61 lines
2 KiB
Python
"""
|
|
FastAPI authentication dependencies.
|
|
|
|
Provides dependency functions for securing REST endpoints with Azure AD token verification.
|
|
"""
|
|
from typing import Optional
|
|
from fastapi import Header, HTTPException, status
|
|
|
|
from app.config import settings
|
|
from app.services.auth_service import verify_access_token
|
|
|
|
|
|
async def get_current_user(authorization: Optional[str] = Header(None)) -> dict:
|
|
"""
|
|
FastAPI dependency to verify the access token and return user claims.
|
|
|
|
Use as a dependency on protected endpoints:
|
|
@app.get("/protected")
|
|
async def protected_route(user: dict = Depends(get_current_user)):
|
|
return {"message": f"Hello {user.get('name')}"}
|
|
|
|
Args:
|
|
authorization: The Authorization header value (Bearer <token>)
|
|
|
|
Returns:
|
|
The token claims dict containing user information
|
|
|
|
Raises:
|
|
HTTPException: 401 if token is missing or invalid
|
|
"""
|
|
# If auth is disabled, return mock user immediately
|
|
if settings.DISABLE_AUTH:
|
|
return {"sub": "dev-user", "name": "Development User", "preferred_username": "dev@localhost"}
|
|
|
|
if not authorization:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Missing authorization header",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
# Extract token from "Bearer <token>" format
|
|
parts = authorization.split()
|
|
if len(parts) != 2 or parts[0].lower() != "bearer":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid authorization header format. Expected: Bearer <token>",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
token = parts[1]
|
|
claims = await verify_access_token(token)
|
|
|
|
if not claims:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid or expired token",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
return claims
|