From e83b9c6cfb7a2a6f9414cf07219dd0067247f830 Mon Sep 17 00:00:00 2001 From: Lior eliav <33252035+LioriE@users.noreply.github.com> Date: Wed, 29 Jan 2025 16:44:08 +0200 Subject: [PATCH] fix: uri bug and add custom username claim option (#220) Co-authored-by: Omer Cohen --- django_descope/authentication.py | 10 +++++++++- django_descope/settings.py | 6 ++++++ django_descope/templatetags/descope.py | 2 +- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/django_descope/authentication.py b/django_descope/authentication.py index f88a503..3a2db68 100644 --- a/django_descope/authentication.py +++ b/django_descope/authentication.py @@ -7,6 +7,7 @@ from django.contrib.auth import logout from django.contrib.auth.backends import BaseBackend from django.http import HttpRequest +from .settings import USERNAME_CLAIM from . import descope_client from .models import DescopeUser @@ -52,7 +53,14 @@ def authenticate(self, request: Union[HttpRequest, None], **kwargs): # Contains sensitive information, so only log in DEBUG mode logger.debug(validated_session) if validated_session: - username = validated_session[SESSION_TOKEN_NAME]["sub"] + try: + username = validated_session[SESSION_TOKEN_NAME][USERNAME_CLAIM] + except KeyError: + logger.error(f"Unable to authenticate user- could not find USERNAME_CLAIM={USERNAME_CLAIM} in Descope JWT") + if settings.DEBUG: + raise + return None + user, _ = DescopeUser.objects.get_or_create(username=username) user.sync(validated_session, refresh_token) request.session[SESSION_COOKIE_NAME] = user.session_token["jwt"] diff --git a/django_descope/settings.py b/django_descope/settings.py index a6663c6..1f10e2e 100644 --- a/django_descope/settings.py +++ b/django_descope/settings.py @@ -19,3 +19,9 @@ # Role names to create in Descope that will map to User attributes IS_STAFF_ROLE = getattr(settings, "DESCOPE_IS_STAFF_ROLE", "is_staff") IS_SUPERUSER_ROLE = getattr(settings, "DESCOPE_IS_SUPERUSER_ROLE", "is_superuser") + +# Ensure the claim used here is present in the JWT. +# Note: It is crucial to use a claim with a unique value for the username. +# Failure to do so may result in unintended user merges or account takeovers. +# For more information, refer to Descope's [NoAuth](https://www.descope.com/blog/post/noauth) blog post. +USERNAME_CLAIM = getattr(settings, "DESCOPE_USERNAME_CLAIM", "sub") diff --git a/django_descope/templatetags/descope.py b/django_descope/templatetags/descope.py index 0264464..af94cab 100644 --- a/django_descope/templatetags/descope.py +++ b/django_descope/templatetags/descope.py @@ -22,7 +22,7 @@ def descope_flow(context, flow_id, success_redirect): id = "descope-" + get_random_string(length=4) store_jwt_url = reverse("django_descope:store_jwt") flow = f""" -