Skip to content

Commit 18fe616

Browse files
committed
Fix authentication to handle Django JWT tokens without decoding as Keycloak tokens
1 parent ca39355 commit 18fe616

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

authorization/authentication.py

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,35 @@ def authenticate(self, request: Request) -> Optional[Tuple[User, str]]:
4343
if not user_info.get("sub"):
4444
raise AuthenticationFailed("Token validation succeeded but missing subject ID")
4545

46+
# Check if this is a Django JWT (already validated user) or Keycloak token
47+
# Django JWTs have 'user_id' in the payload, Keycloak tokens don't
48+
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
49+
from rest_framework_simplejwt.tokens import AccessToken
50+
51+
try:
52+
# Try to decode as Django JWT
53+
access_token = AccessToken(token) # type: ignore[arg-type]
54+
user_id = access_token.get("user_id")
55+
56+
if user_id:
57+
# This is a Django JWT - user is already synced, just get from DB
58+
user = User.objects.get(id=user_id)
59+
return (user, token)
60+
except (TokenError, InvalidToken, User.DoesNotExist):
61+
# Not a Django JWT or user not found, continue with Keycloak flow
62+
pass
63+
64+
# This is a Keycloak token - sync the user
4665
# Get user roles and organizations from the token
4766
roles = keycloak_manager.get_user_roles(token)
4867
organizations = keycloak_manager.get_user_organizations(token)
4968

5069
# Sync the user information with our database
51-
user = keycloak_manager.sync_user_from_keycloak(user_info, roles, organizations)
52-
if not user:
70+
synced_user = keycloak_manager.sync_user_from_keycloak(user_info, roles, organizations)
71+
if not synced_user:
5372
raise AuthenticationFailed("Failed to synchronize user information")
5473

55-
return (user, token)
74+
return (synced_user, token)
5675

5776
def authenticate_header(self, request: Request) -> str:
5877
"""

0 commit comments

Comments
 (0)