[Django]-Django-OIDC with keycloak – OIDC callback state not found in session oidc_states

0👍

Thanks for the support.

The issue has been resolved by recreating the user in keycloak with full details.

Please finds the screenshot.Keycloak user creation

Cheers
SG

0👍

The key issue is here that keycloak_oidc is used, specifically notice the AUTHENTICATION_BACKENDS. It is a project that synchronizes the attributes found in OIDC with the local Django installation, unlike mozilla-django-oidc which merely does authentication. The answer above is the key to solving this issue, once the email address (plus first and lastname) are not provided it cannot be added to Django. It is likely that this fails to with any OIDC provider which does not add these attributes. I have added an issue upstream.

0👍

You needs add class of authentication backend and orverride create_user method to add is_staff or is_superuser to True.
Add AUTHENTICATION_BACKENDS in settings.py refering to you custom class backent
Example:

# auth_backends.py

from mozilla_django_oidc.auth import OIDCAuthenticationBackend


class KeycloakOIDCAuthenticationBackend(OIDCAuthenticationBackend):

    def create_user(self, claims):
        """ Overrides Authentication Backend so that Django users are
            created with the keycloak preferred_username.
            If nothing found matching the email, then try the username.
        """
        user = super(KeycloakOIDCAuthenticationBackend, self).create_user(claims)
        user.first_name = claims.get('given_name', '')
        user.last_name = claims.get('family_name', '')
        user.email = claims.get('email')
        user.is_staff = True #Here the fix that error
        user.username = claims.get('preferred_username')
        user.save()
        return user

    def filter_users_by_claims(self, claims):
        """ Return all users matching the specified email.
            If nothing found matching the email, then try the username
        """
        email = claims.get('email')

        if not email:
            return self.UserModel.objects.none()
        users = self.UserModel.objects.filter(email__iexact=email)
        return users

    def update_user(self, user, claims):
        user.first_name = claims.get('given_name', '')
        user.last_name = claims.get('family_name', '')
        user.email = claims.get('email')
        user.save()
        return user

In settings.py

#settings.py
AUTHENTICATION_BACKENDS = (
    'my_app.auth_backends.KeycloakOIDCAuthenticationBackend',
)

Leave a comment