Skip to content

Commit

Permalink
fix: uri bug and add custom username claim option (#220)
Browse files Browse the repository at this point in the history
Co-authored-by: Omer Cohen <[email protected]>
  • Loading branch information
LioriE and omercnet authored Jan 29, 2025
1 parent 2800283 commit e83b9c6
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
10 changes: 9 additions & 1 deletion django_descope/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"]
Expand Down
6 changes: 6 additions & 0 deletions django_descope/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
2 changes: 1 addition & 1 deletion django_descope/templatetags/descope.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""
<descope-wc id="{id}" project-id="{PROJECT_ID}" flow-id="{flow_id}" redirect-url="{success_redirect}"
<descope-wc id="{id}" project-id="{PROJECT_ID}" flow-id="{flow_id}" redirect-url="{context.request.build_absolute_uri()}"
base-url="{os.environ.get('DESCOPE_BASE_URI', '')}"></descope-wc>
<script>
const descopeWcEle = document.getElementById('{id}');
Expand Down

0 comments on commit e83b9c6

Please sign in to comment.