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 passlib.context import CryptContext
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
from app.schemas.token import TokenPayload, TokenResponse
|
from app.schemas.token import TokenPayload, TokenResponse
|
||||||
|
from jose.exceptions import ExpiredSignatureError, JWTError, JOSEError
|
||||||
|
|
||||||
# Configuration
|
# Configuration
|
||||||
SECRET_KEY = settings.SECRET_KEY
|
SECRET_KEY = settings.SECRET_KEY
|
||||||
@@ -116,12 +117,19 @@ def decode_token(token: str, required_type: str = "access") -> TokenPayload:
|
|||||||
jti=payload.get("jti")
|
jti=payload.get("jti")
|
||||||
)
|
)
|
||||||
|
|
||||||
except KeyError as e:
|
except ExpiredSignatureError as e: # Expired token
|
||||||
raise JWTError("Malformed token. Missing required claim.") from e
|
|
||||||
except ExpiredSignatureError as e:
|
|
||||||
raise JWTError("Token expired. Please refresh your token to continue.") from e
|
raise JWTError("Token expired. Please refresh your token to continue.") from e
|
||||||
except JWTError as 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
|
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