Spaces:
Sleeping
Sleeping
File size: 6,064 Bytes
5be081e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | """
JWT Authentication Middleware for Todo API
Owner: Backend Security Engineer
Purpose: JWT token verification and user_id extraction
Architecture: FastAPI dependency injection with python-jose
Constitutional Constraints:
- REQUIRED: Verify JWT signature using BETTER_AUTH_SECRET
- REQUIRED: Validate issuer="todoweb" and audience="todoweb-api"
- REQUIRED: Extract user_id from "sub" claim
- REQUIRED: Return 401 for invalid/expired/missing tokens
- REQUIRED: Use HTTPBearer security scheme
Security Protocol:
1. Extract token from Authorization: Bearer <token> header
2. Verify signature with shared BETTER_AUTH_SECRET
3. Validate token claims (exp, iss, aud)
4. Extract user_id from sub claim
5. Return user_id for use in route handlers
All protected routes MUST use Depends(get_current_user_id) to enforce authentication.
"""
import os
import logging
from typing import Annotated, Optional
from fastapi import HTTPException, Security, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from jose import jwt, JWTError
from jose.exceptions import ExpiredSignatureError, JWTClaimsError
from dotenv import load_dotenv
# Configure logging
logger = logging.getLogger("api.auth")
# Load environment variables
load_dotenv()
# HTTPBearer security scheme for JWT tokens
security = HTTPBearer(
scheme_name="Bearer",
description="JWT token from Better Auth. Include in Authorization header as 'Bearer <token>'",
auto_error=False
)
def get_better_auth_secret() -> str:
"""
Get BETTER_AUTH_SECRET from environment.
Returns:
BETTER_AUTH_SECRET string
Raises:
HTTPException(500): If BETTER_AUTH_SECRET is not configured
"""
secret = os.getenv("BETTER_AUTH_SECRET")
if not secret:
logger.error("BETTER_AUTH_SECRET environment variable not set")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Server configuration error: Authentication secret not configured"
)
return secret
def verify_token(credentials: HTTPAuthorizationCredentials) -> dict:
"""
Verify JWT token and extract payload.
Validates:
- Token signature using BETTER_AUTH_SECRET
- Token expiration (exp claim)
- Issuer claim (iss="todoweb")
- Audience claim (aud="todoweb-api")
Args:
credentials: HTTPAuthorizationCredentials from HTTPBearer
Returns:
dict: Decoded JWT payload containing user_id in "sub" claim
Raises:
HTTPException(401): If token is invalid, expired, or has invalid claims
"""
token = credentials.credentials
secret = get_better_auth_secret()
try:
# Decode and verify JWT token
payload = jwt.decode(
token,
secret,
algorithms=["HS256"],
issuer="todoweb",
audience="todoweb-api"
)
logger.debug(f"Token verified successfully for user: {payload.get('sub')}")
return payload
except ExpiredSignatureError:
logger.warning("Token verification failed: Token has expired")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token has expired",
headers={"WWW-Authenticate": "Bearer"}
)
except JWTClaimsError as e:
logger.warning(f"Token verification failed: Invalid token claims - {e}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token claims (issuer or audience mismatch)",
headers={"WWW-Authenticate": "Bearer"}
)
except JWTError as e:
logger.warning(f"Token verification failed: {e}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication token",
headers={"WWW-Authenticate": "Bearer"}
)
async def get_current_user_id(
credentials: Annotated[Optional[HTTPAuthorizationCredentials], Security(security)] = None
) -> str:
"""
FastAPI dependency to extract user_id from JWT token.
This is the primary authentication dependency for all protected routes.
Args:
credentials: Automatically extracted from Authorization header
Returns:
str: User ID from JWT "sub" claim
Raises:
HTTPException(401): If token is missing, invalid, or missing user_id
"""
if not credentials:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
headers={"WWW-Authenticate": "Bearer"}
)
# Verify token and extract payload
payload = verify_token(credentials)
# Extract user_id from "sub" claim
user_id = payload.get("sub")
if not user_id:
logger.error("Token verification succeeded but 'sub' claim is missing")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token: missing user ID",
headers={"WWW-Authenticate": "Bearer"}
)
return user_id
# Optional: Additional dependency for extracting full user info
async def get_current_user_info(
credentials: Annotated[HTTPAuthorizationCredentials, Security(security)]
) -> dict:
"""
FastAPI dependency to extract full user information from JWT token.
Returns the complete JWT payload including:
- sub: User ID
- email: User email (if present)
- iat: Issued at timestamp
- exp: Expiration timestamp
Usage:
@router.get("/api/profile")
async def get_profile(
user_info: Annotated[dict, Depends(get_current_user_info)]
):
return {
"user_id": user_info["sub"],
"email": user_info.get("email")
}
Args:
credentials: Automatically extracted from Authorization header
Returns:
dict: Complete JWT payload
Raises:
HTTPException(401): If token is invalid
"""
return verify_token(credentials)
|