Skip to content

Commit e83b9c6

Browse files
LioriEomercnet
andauthored
fix: uri bug and add custom username claim option (#220)
Co-authored-by: Omer Cohen <omer@descope.com>
1 parent 2800283 commit e83b9c6

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

django_descope/authentication.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from django.contrib.auth import logout
88
from django.contrib.auth.backends import BaseBackend
99
from django.http import HttpRequest
10+
from .settings import USERNAME_CLAIM
1011

1112
from . import descope_client
1213
from .models import DescopeUser
@@ -52,7 +53,14 @@ def authenticate(self, request: Union[HttpRequest, None], **kwargs):
5253
# Contains sensitive information, so only log in DEBUG mode
5354
logger.debug(validated_session)
5455
if validated_session:
55-
username = validated_session[SESSION_TOKEN_NAME]["sub"]
56+
try:
57+
username = validated_session[SESSION_TOKEN_NAME][USERNAME_CLAIM]
58+
except KeyError:
59+
logger.error(f"Unable to authenticate user- could not find USERNAME_CLAIM={USERNAME_CLAIM} in Descope JWT")
60+
if settings.DEBUG:
61+
raise
62+
return None
63+
5664
user, _ = DescopeUser.objects.get_or_create(username=username)
5765
user.sync(validated_session, refresh_token)
5866
request.session[SESSION_COOKIE_NAME] = user.session_token["jwt"]

django_descope/settings.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,9 @@
1919
# Role names to create in Descope that will map to User attributes
2020
IS_STAFF_ROLE = getattr(settings, "DESCOPE_IS_STAFF_ROLE", "is_staff")
2121
IS_SUPERUSER_ROLE = getattr(settings, "DESCOPE_IS_SUPERUSER_ROLE", "is_superuser")
22+
23+
# Ensure the claim used here is present in the JWT.
24+
# Note: It is crucial to use a claim with a unique value for the username.
25+
# Failure to do so may result in unintended user merges or account takeovers.
26+
# For more information, refer to Descope's [NoAuth](https://www.descope.com/blog/post/noauth) blog post.
27+
USERNAME_CLAIM = getattr(settings, "DESCOPE_USERNAME_CLAIM", "sub")

django_descope/templatetags/descope.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def descope_flow(context, flow_id, success_redirect):
2222
id = "descope-" + get_random_string(length=4)
2323
store_jwt_url = reverse("django_descope:store_jwt")
2424
flow = f"""
25-
<descope-wc id="{id}" project-id="{PROJECT_ID}" flow-id="{flow_id}" redirect-url="{success_redirect}"
25+
<descope-wc id="{id}" project-id="{PROJECT_ID}" flow-id="{flow_id}" redirect-url="{context.request.build_absolute_uri()}"
2626
base-url="{os.environ.get('DESCOPE_BASE_URI', '')}"></descope-wc>
2727
<script>
2828
const descopeWcEle = document.getElementById('{id}');

0 commit comments

Comments
 (0)