From 3912537477e39857344fd69be5b95bed287a8b07 Mon Sep 17 00:00:00 2001 From: Felipe Cardoso Date: Fri, 28 Feb 2025 17:01:57 +0100 Subject: [PATCH] Handle additional JWT and JOSE error cases in token validation. Expanded exception handling to cover more specific JWT and JOSE-related errors, including signature verification failures and malformed tokens. This ensures better error messaging and robustness in token validation. --- backend/app/auth/security.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/backend/app/auth/security.py b/backend/app/auth/security.py index da6ba37..5559dec 100644 --- a/backend/app/auth/security.py +++ b/backend/app/auth/security.py @@ -7,6 +7,7 @@ from jose import jwt, ExpiredSignatureError, JWTError from passlib.context import CryptContext from app.core.config import settings from app.schemas.token import TokenPayload, TokenResponse +from jose.exceptions import ExpiredSignatureError, JWTError, JOSEError # Configuration SECRET_KEY = settings.SECRET_KEY @@ -116,12 +117,19 @@ def decode_token(token: str, required_type: str = "access") -> TokenPayload: jti=payload.get("jti") ) - except KeyError as e: - raise JWTError("Malformed token. Missing required claim.") from e - except ExpiredSignatureError as e: + except ExpiredSignatureError as e: # Expired token raise JWTError("Token expired. Please refresh your token to continue.") from e except JWTError as e: + # Handle signature verification and malformed token errors + if str(e) in ["Signature verification failed.", "Not enough segments"]: + raise JWTError("Invalid token.") from e + # Propagate other JWTError messages raise JWTError(str(e)) from e + except KeyError as e: # Missing required claims + raise JWTError("Malformed token. Missing required claim.") from e + except JOSEError as e: # All other JOSE-related errors + raise JWTError("Invalid token.") from e +