Skip to content

Commit a1e542c

Browse files
authored
Merge pull request #543 from Robin-Van-de-Merghel/robin-fix-verify-token
[BUG] fix: Fixed verify_token error
2 parents caf6607 + ef04d27 commit a1e542c

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

diracx-routers/src/diracx/routers/utils/users.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from fastapi import Depends, HTTPException, status
88
from fastapi.security import OpenIdConnect
9+
from joserfc.errors import JoseError
910
from joserfc.jwt import JWTClaimsRegistry
1011
from pydantic import BaseModel, GetCoreSchemaHandler, GetJsonSchemaHandler
1112
from pydantic_core import CoreSchema, core_schema
@@ -97,7 +98,7 @@ async def verify_dirac_access_token(
9798
iss={"essential": True, "value": settings.token_issuer},
9899
),
99100
)
100-
except ValueError as e:
101+
except (ValueError, JoseError) as e:
101102
raise HTTPException(
102103
status_code=status.HTTP_401_UNAUTHORIZED,
103104
detail="Invalid JWT",

diracx-routers/tests/auth/test_standard.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,40 @@ async def test_refresh_token_expired(
594594
assert data["detail"] == "Invalid JWT: expired_token: The token is expired"
595595

596596

597+
async def test_access_token_expired(
598+
test_client, test_auth_settings: AuthSettings, auth_httpx_mock: HTTPXMock
599+
):
600+
"""Test the expiration date of the passed access token.
601+
- get an access token
602+
- decode it and change the expiration time
603+
- recode it (with the JWK of the server).
604+
"""
605+
# Get access token
606+
initial_access_token = _get_tokens(test_client)["access_token"]
607+
608+
# Decode it
609+
access_payload = jwt.decode(
610+
initial_access_token, options={"verify_signature": False}
611+
)
612+
613+
# Modify the expiration time (utc now - 5 hours)
614+
access_payload["exp"] = int(
615+
(datetime.now(tz=timezone.utc) - timedelta(hours=5)).timestamp()
616+
)
617+
618+
# Encode it differently
619+
new_access_token = create_token(access_payload, test_auth_settings)
620+
621+
headers = {"Authorization": f"Bearer {new_access_token}"}
622+
623+
# Try to get the userinfo using the invalid access token
624+
# The server should detect that it is not encoded properly
625+
r = test_client.get("/api/auth/userinfo", headers=headers)
626+
data = r.json()
627+
assert r.status_code == 401, data
628+
assert data["detail"] == "Invalid JWT"
629+
630+
597631
async def test_refresh_token_rotated_expiration_time(
598632
test_client, test_auth_settings: AuthSettings, auth_httpx_mock: HTTPXMock
599633
):

0 commit comments

Comments
 (0)