Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for decoding JWT tokens #3

Merged
merged 7 commits into from
Feb 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 19 additions & 21 deletions django_keycloak/backends.py
Original file line number Diff line number Diff line change
@@ -1,47 +1,45 @@
from django.contrib.auth.backends import RemoteUserBackend
from django.contrib.auth import get_user_model
from django_keycloak.keycloak import Connect
from django_keycloak.models import KeycloakUserAutoId


class KeycloakAuthenticationBackend(RemoteUserBackend):

def authenticate(self, request, username=None, password=None):
keycloak = Connect()
token = keycloak.get_token_from_credentials(username, password).get("access_token")
user = get_user_model()
User = get_user_model()
if not keycloak.is_token_active(token):
return
try:
user = user.objects.get(username=username)
# Get user info based on token
user_info = keycloak.get_user_info(token)

# Get user info and update
user.first_name = user_info.get('given_name')
user.last_name = user_info.get('family_name')
user.email = user_info.get('email')
user.save()

except user.DoesNotExist:
user = user.objects.create_user(username, password)

user = User.objects.get(username=username)
if isinstance(user, KeycloakUserAutoId):
# Get user info based on token
user_info = keycloak.get_user_info(token)

# Get user info and update
user.first_name = user_info.get('given_name')
user.last_name = user_info.get('family_name')
user.email = user_info.get('email')
except User.DoesNotExist:
user = User.objects.create_user(username, password)
if keycloak.has_superuser_perm(token):
user.is_staff = True
user.is_superuser = True
user.save()
else:
user.is_staff = False
user.is_superuser = False
user.save()
user.save()

return user

def get_user(self, user_identifier):
user = get_user_model()
User = get_user_model()
try:
return user.objects.get(username=user_identifier)
except user.DoesNotExist:
return User.objects.get(username=user_identifier)
except User.DoesNotExist:
try:
return user.objects.get(id=user_identifier)
except user.DoesNotExist:
return User.objects.get(id=user_identifier)
except User.DoesNotExist:
return None
Loading