mozilla / mozilla-django-oidc

A django OpenID Connect library
https://mozilla-django-oidc.readthedocs.io
Mozilla Public License 2.0
444 stars 166 forks source link

Allow SessionRefresh middleware subclass to easily accept dynamic request parameters in process_request method #527

Open jordan-owen opened 6 months ago

jordan-owen commented 6 months ago

I'm overriding the process_request method of SessionRefresh to dynamically add a parameter kc_idp_hint. This parameter is different for each user, so I can't use OIDC_AUTH_REQUEST_EXTRA_PARAMS. There should be an easier way to add parameters to a subclassed SessionRefresh.

from django.urls import reverse
from django.utils.functional import cached_property
from mozilla_django_oidc.middleware import SessionRefresh
from django.conf import settings

class CustomSessionRefresh(SessionRefresh):
    """
    This class extends the SessionRefresh middleware.
    """

    def process_request(self, request):
        """
        Override the process_request method to add kc_idp_hint to the OIDC_AUTH_REQUEST_EXTRA_PARAMS.
        """

        if request.user.is_authenticated and not request.user.is_anonymous:

            # NOTE: Modifying settings dynamically isn't good, but needed here to avoid code duplication
            settings.OIDC_AUTH_REQUEST_EXTRA_PARAMS = {
                "kc_idp_hint": request.user.userprofile.keycloak_identity_provider.name,
            }

        return super().process_request(request)
jordan-owen commented 6 months ago

Suggest a similar approach to OIDCAuthenticationRequestView.

class CustomOIDCAuthenticationRequestView(OIDCAuthenticationRequestView):
    """
    Overrride OIDCAuthenticationRequestView to add kc_idp_hint parameter.
    """

    def get_extra_params(self, request):
        keycloak_identity_provider = request.GET.get("kc_idp_hint")
        extra_params = super().get_extra_params(request)
        extra_params["kc_idp_hint"] = keycloak_identity_provider
        return extra_params