From e8d52dc93516ca794efaadb75f00775abdf604a0 Mon Sep 17 00:00:00 2001 From: Benedikt Nordhoff Date: Mon, 20 May 2024 19:06:01 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20fix:=20Proper=20response=20on=20?= =?UTF-8?q?authorization=20failures=20(#37)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- middleware.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/middleware.py b/middleware.py index 83d3589..30dec8d 100644 --- a/middleware.py +++ b/middleware.py @@ -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 @@ -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: @@ -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")