Skip to content

Commit

Permalink
🔧 fix: Proper response on authorization failures (#37)
Browse files Browse the repository at this point in the history
Raising an HTTPException in the middleware does not return the expected response and the exception including the stack trace is propagated to the console, producing a huge amount of logs.

This explicitly returns the expected response and only logs the reason.
  • Loading branch information
bnord01 authored May 20, 2024
1 parent 053007a commit e8d52dc
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions middleware.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
from datetime import datetime, timezone
from fastapi import Request, HTTPException
from fastapi import Request
from fastapi.responses import JSONResponse
from jose import jwt, JWTError
from config import logger

Expand All @@ -20,7 +21,8 @@ async def next():
if jwt_secret:
authorization = request.headers.get('Authorization')
if not authorization or not authorization.startswith('Bearer '):
raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")
logger.info(f"Unauthorized request with missing or invalid Authorization header to: {request.url.path}")
return JSONResponse(status_code=401, content = { "detail" : "Missing or invalid Authorization header" })

token = authorization.split(' ')[1]
try:
Expand All @@ -32,12 +34,14 @@ async def next():
exp_datetime = datetime.fromtimestamp(exp_timestamp, tz=timezone.utc)
current_datetime = datetime.now(tz=timezone.utc)
if current_datetime > exp_datetime:
raise HTTPException(status_code=401, detail="Token has expired")
logger.info(f"Unauthorized request with expired token to: {request.url.path}")
return JSONResponse(status_code=401, content = { "detail" : "Token has expired" })

request.state.user = payload
logger.debug(f"{request.url.path} - {payload}")
except JWTError as e:
raise HTTPException(status_code=401, detail=f"Invalid token: {str(e)}")
logger.info(f"Unauthorized request with invalid token to: {request.url.path}, reason: {str(e)}")
return JSONResponse(status_code=401, content = { "detail" : f"Invalid token: {str(e)}" })
else:
logger.warn("JWT_SECRET not found in environment variables")

Expand Down

0 comments on commit e8d52dc

Please sign in to comment.