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.
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user