From d099e0b9c697508645a4d622b1490be20cb43b35 Mon Sep 17 00:00:00 2001 From: Ana Rute Mendes Date: Mon, 27 Nov 2023 11:54:12 +0100 Subject: [PATCH] Raise error when token has expired This gives a better response to the user --- api/auth/auth_handler.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/api/auth/auth_handler.py b/api/auth/auth_handler.py index 5ab8ebc19..165cb8bc3 100644 --- a/api/auth/auth_handler.py +++ b/api/auth/auth_handler.py @@ -3,6 +3,8 @@ from jwt import PyJWKClient from datetime import datetime, timedelta from decouple import config +from fastapi import HTTPException + JWT_SECRET = config("JWT_SECRET") JWT_ALGORITHM = config("JWT_ALGORITHM") @@ -23,7 +25,10 @@ def decode_token(token: str) -> dict: jwks_client = PyJWKClient(OIDC_CERTS_URL) test = jwks_client.get_signing_key_from_jwt(token) signing_key = test.key - decoded_token = jwt.decode(token, signing_key, audience=JWT_AUDIENCE, algorithms=[JWT_ALGORITHM]) + try: + decoded_token = jwt.decode(token, signing_key, audience=JWT_AUDIENCE, algorithms=[JWT_ALGORITHM]) + except jwt.exceptions.ExpiredSignatureError: + raise HTTPException(status_code=401, detail="Token expired. Please authenticate again.") return decoded_token if decoded_token["exp"] >= time.time() else None