From 44b23b8ab9bef49574870075a60cabd3995740a9 Mon Sep 17 00:00:00 2001 From: Vianpyro Date: Wed, 20 Nov 2024 18:27:22 -0500 Subject: [PATCH 1/2] Enhance token verification to check for required token types in JWT handling --- jwt_helper.py | 9 ++++++--- routes/authentication.py | 6 +++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/jwt_helper.py b/jwt_helper.py index 8a8cf01..dabfb93 100644 --- a/jwt_helper.py +++ b/jwt_helper.py @@ -55,12 +55,15 @@ def extract_token_from_header() -> str: return auth_header.split("Bearer ")[1] -def verify_token(token: str) -> dict: +def verify_token(token: str, required_type: str) -> dict: """ Verify and decode a JWT token. """ try: - return jwt.decode(token, SECRET_KEY, algorithms=["HS256"]) + decoded = jwt.decode(token, SECRET_KEY, algorithms=["HS256"]) + if decoded.get("token_type") != required_type: + raise jwt.InvalidTokenError("Invalid token type") + return decoded except jwt.ExpiredSignatureError: raise TokenError("Token has expired", 401) except jwt.InvalidTokenError: @@ -76,7 +79,7 @@ def token_required(f): def decorated(*args, **kwargs): try: token = extract_token_from_header() - decoded = verify_token(token) + decoded = verify_token(token, required_type="access") request.player_id = decoded["player_id"] return f(*args, **kwargs) except TokenError as e: diff --git a/routes/authentication.py b/routes/authentication.py index 247255a..5befde2 100644 --- a/routes/authentication.py +++ b/routes/authentication.py @@ -8,11 +8,11 @@ from db import get_db_connection from jwt_helper import ( + TokenError, + extract_token_from_header, generate_access_token, generate_refresh_token, verify_token, - extract_token_from_header, - TokenError, ) load_dotenv() @@ -117,7 +117,7 @@ def login(): def refresh_token(): try: token = extract_token_from_header() - decoded = verify_token(token) + decoded = verify_token(token, required_type="refresh") player_id = decoded["player_id"] new_access_token = generate_access_token(player_id) From 1b5e07217d4440dfebfcdb9d09833951372f7ce7 Mon Sep 17 00:00:00 2001 From: Vianpyro Date: Wed, 20 Nov 2024 18:33:26 -0500 Subject: [PATCH 2/2] Add token type to access and refresh token payloads --- jwt_helper.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jwt_helper.py b/jwt_helper.py index dabfb93..ece086e 100644 --- a/jwt_helper.py +++ b/jwt_helper.py @@ -29,6 +29,7 @@ def generate_access_token(player_id: int) -> str: "player_id": player_id, "exp": datetime.now(timezone.utc) + ACCESS_TOKEN_EXPIRY, # Expiration "iat": datetime.now(timezone.utc), # Issued at + "token_type": "access", } return jwt.encode(payload, SECRET_KEY, algorithm="HS256") @@ -41,6 +42,7 @@ def generate_refresh_token(player_id: int) -> str: "player_id": player_id, "exp": datetime.now(timezone.utc) + REFRESH_TOKEN_EXPIRY, "iat": datetime.now(timezone.utc), + "token_type": "refresh", } return jwt.encode(payload, SECRET_KEY, algorithm="HS256")