Registering new users using Keycloak with Django
An earlier post introduced using Keycloak as an Identity and Access Management (IAM) system with Django. Keycloak allows you to add authentication to applications and secure services easily as it handles storing and authenticating users. However, the mozilla-django-oidc library does not include a direct registration URL.
We can add a URL for direct registration by making use of another OpenID Connect (OIDC) endpoint.
Add the OIDC registration endpoint to settings.py
.
# app/settings.py
# Your OIDC server
OIDC_HOST = "https://auth.example.com"
# Your OIDC realm
OIDC_REALM = "realm-name"
# Additional URL for registration
OIDC_OP_REGISTRATION_ENDPOINT = f"{OIDC_HOST}/realms/{OIDC_REALM}/protocol/openid-connect/registrations"
Create a new RedirectView
to redirect the user to the OIDC endpoint.
You will wish to change show_my_account_url_name
to the name of the URL you wish
to redirect the user to after registration.
You may wish to customise the kc_locale
parameter, or use urllib.parse.urlparse
and urllib.parse.urlunparse
to build the registration_url
.
# app/views.py
from django.conf import settings
from django.urls import reverse
from django.views.generic.base import RedirectView
from urllib.parse import urlencode
class KeycloakOIDCRegistration(RedirectView):
"""Generate link for user registration with Keycloak."""
def get_redirect_url(self, *args, **kwargs):
registration_url = (
settings.OIDC_OP_REGISTRATION_ENDPOINT
+ "?"
+ urlencode(
{
"client_id": settings.OIDC_RP_CLIENT_ID,
"response_type": "code",
"scope": "openid email",
"redirect_uri": self.request.build_absolute_uri(
location=reverse("show_my_account_url_name")
),
"kc_locale": "en",
}
)
)
return registration_url
Add a new URL in your urls.py
and make use of the RedirectView
created above.
# app/urls.py
from . import views
urlpatterns = [
...
path("/accounts/register", views.KeycloakOIDCRegistration.as_view(), name='register_account'),
...
]