authentik.providers.saml.views.sso

authentik SAML IDP Views

  1"""authentik SAML IDP Views"""
  2
  3from django.http import Http404, HttpRequest, HttpResponse
  4from django.shortcuts import get_object_or_404
  5from django.utils.decorators import method_decorator
  6from django.utils.translation import gettext as _
  7from django.views.decorators.clickjacking import xframe_options_sameorigin
  8from django.views.decorators.csrf import csrf_exempt
  9from structlog.stdlib import get_logger
 10
 11from authentik.common.saml.exceptions import CannotHandleAssertion
 12from authentik.core.models import Application
 13from authentik.events.models import Event, EventAction
 14from authentik.events.signals import get_login_event
 15from authentik.flows.apps import ContinuousLogin
 16from authentik.flows.exceptions import FlowNonApplicableException
 17from authentik.flows.models import FlowStageBinding, in_memory_stage
 18from authentik.flows.planner import PLAN_CONTEXT_APPLICATION, PLAN_CONTEXT_SSO, FlowPlanner
 19from authentik.flows.views.executor import SESSION_KEY_POST
 20from authentik.lib.utils.errors import exception_to_dict
 21from authentik.lib.views import bad_request_message
 22from authentik.policies.views import PolicyAccessView
 23from authentik.providers.saml.models import SAMLBindings, SAMLProvider
 24from authentik.providers.saml.processors.authn_request_parser import (
 25    AuthNRequest,
 26    AuthNRequestParser,
 27)
 28from authentik.providers.saml.views.flows import (
 29    PLAN_CONTEXT_SAML_AUTH_N_REQUEST,
 30    REQUEST_KEY_RELAY_STATE,
 31    REQUEST_KEY_SAML_REQUEST,
 32    REQUEST_KEY_SAML_SIG_ALG,
 33    REQUEST_KEY_SAML_SIGNATURE,
 34    SAMLFlowFinalView,
 35)
 36from authentik.stages.consent.stage import (
 37    PLAN_CONTEXT_CONSENT_HEADER,
 38    PLAN_CONTEXT_CONSENT_PERMISSIONS,
 39)
 40
 41LOGGER = get_logger()
 42
 43SESSION_KEY_LAST_LOGIN_UID = "authentik/providers/saml/last_login_uid"
 44
 45
 46class SAMLSSOView(PolicyAccessView):
 47    """SAML SSO Base View, which plans a flow and injects our final stage.
 48    Calls get/post handler."""
 49
 50    def __init__(self, **kwargs):
 51        super().__init__(**kwargs)
 52        self.plan_context = {}
 53
 54    def resolve_provider_application(self):
 55        self.application = get_object_or_404(Application, slug=self.kwargs["application_slug"])
 56        self.provider: SAMLProvider = get_object_or_404(
 57            SAMLProvider, pk=self.application.provider_id
 58        )
 59
 60    def continuous_login_hold_required(self) -> bool:
 61        """Conservatively hold tabs when authorization may require the flow executor.
 62
 63        Stage policies can depend on the user who is about to authenticate, so they cannot be
 64        evaluated accurately here. An entirely empty flow is the only flow known to be safe.
 65        """
 66        # TODO: Revisit once #27280 lands, which holds tabs behind a single auto-redirecting source.
 67        return FlowStageBinding.objects.filter(target=self.provider.authorization_flow).exists()
 68
 69    def check_saml_request(self) -> HttpRequest | None:
 70        """Handler to verify the SAML Request. Must be implemented by a subclass"""
 71        raise NotImplementedError
 72
 73    def saml_request_error(self, exc: CannotHandleAssertion) -> HttpResponse:
 74        """Record the full error for administrators and show the user only the safe message"""
 75        message = str(exc)
 76        context = {}
 77        if isinstance(exc.detail, Exception):
 78            context["exception"] = exception_to_dict(exc.detail)
 79        elif exc.detail:
 80            context["detail"] = str(exc.detail)
 81        Event.new(
 82            EventAction.CONFIGURATION_ERROR,
 83            provider=self.provider,
 84            message=message,
 85            **context,
 86        ).save()
 87        LOGGER.info(
 88            "Failed to process SAML request",
 89            provider=self.provider.name,
 90            message=message,
 91            detail=exc.detail,
 92        )
 93        return bad_request_message(self.request, message)
 94
 95    def get_resume_url(self) -> str | None:
 96        """URL to re-enter this SAML request after another tab authenticated."""
 97        return None
 98
 99    def get(self, request: HttpRequest, application_slug: str) -> HttpResponse:
100        """Verify the SAML Request, and if valid initiate the FlowPlanner for the application"""
101        # Call the method handler, which checks the SAML
102        # Request and returns a HTTP Response on error
103        method_response = self.check_saml_request()
104        if method_response:
105            return method_response
106        # If the SP requested ForceAuthn, we must re-authenticate the user regardless of
107        # any existing session, mirroring the OIDC provider's prompt=login handling.
108        # The provider can be configured to ignore the attribute, in which case the
109        # existing session is used as if ForceAuthn had not been set.
110        auth_n_request: AuthNRequest | None = self.plan_context.get(
111            PLAN_CONTEXT_SAML_AUTH_N_REQUEST
112        )
113        if auth_n_request and auth_n_request.force_authn and not self.provider.ignore_force_authn:
114            reauth_response = self.check_force_authn(request)
115            if reauth_response:
116                return reauth_response
117        # Regardless, we start the planner and return to it
118        planner = FlowPlanner(self.provider.authorization_flow)
119        planner.allow_empty_flows = True
120        try:
121            plan = planner.plan(
122                request,
123                {
124                    PLAN_CONTEXT_SSO: True,
125                    PLAN_CONTEXT_APPLICATION: self.application,
126                    PLAN_CONTEXT_CONSENT_HEADER: _("You're about to sign into %(application)s.")
127                    % {"application": self.application.name},
128                    PLAN_CONTEXT_CONSENT_PERMISSIONS: [],
129                    **self.plan_context,
130                },
131            )
132        except FlowNonApplicableException:
133            raise Http404 from None
134        plan.append_stage(in_memory_stage(SAMLFlowFinalView))
135        return plan.to_redirect(
136            request,
137            self.provider.authorization_flow,
138            next=self.get_resume_url(),
139            allowed_silent_types=(
140                [SAMLFlowFinalView]
141                if self.provider.sp_binding in [SAMLBindings.POST, SAMLBindings.REDIRECT]
142                # Under continuous login, other tabs hold whenever the authorization flow has
143                # bound stages, and only the flow interface tells them when this tab is done.
144                and (not ContinuousLogin.get() or not self.continuous_login_hold_required())
145                else []
146            ),
147        )
148
149    def post(self, request: HttpRequest, application_slug: str) -> HttpResponse:
150        """GET and POST use the same handler, but we can't
151        override .dispatch easily because PolicyAccessView's dispatch"""
152        return self.get(request, application_slug)
153
154    def check_force_authn(self, request: HttpRequest) -> HttpResponse | None:
155        """Trigger re-authentication when the AuthnRequest carries ForceAuthn. Returns a
156        redirect into the authentication flow if re-auth is still required, otherwise
157        None to let the SSO flow proceed."""
158        login_event = get_login_event(request)
159        login_uid = str(login_event.pk) if login_event else None
160        # Re-authenticate if it hasn't happened yet: either we have no record of a forced
161        # login for this session, or the session's login event still matches the one we
162        # saw before redirecting to the authentication flow. Once the user re-logs in, a
163        # new login event is created, the UID changes, and we stop forcing re-auth.
164        if (
165            SESSION_KEY_LAST_LOGIN_UID not in request.session
166            or login_uid == request.session[SESSION_KEY_LAST_LOGIN_UID]
167        ):
168            request.session[SESSION_KEY_LAST_LOGIN_UID] = login_uid
169            return self.handle_no_permission()
170        return None
171
172
173class SAMLSSOBindingRedirectView(SAMLSSOView):
174    """SAML Handler for SSO/Redirect bindings, which are sent via GET"""
175
176    def get_resume_url(self) -> str | None:
177        return self.request.get_full_path()
178
179    def check_saml_request(self) -> HttpRequest | None:
180        """Handle REDIRECT bindings"""
181        if REQUEST_KEY_SAML_REQUEST not in self.request.GET:
182            LOGGER.info("SAML payload missing")
183            return bad_request_message(self.request, _("The SAML request payload is missing."))
184
185        try:
186            auth_n_request = AuthNRequestParser(self.provider).parse_detached(
187                self.request.GET[REQUEST_KEY_SAML_REQUEST],
188                self.request.GET.get(REQUEST_KEY_RELAY_STATE),
189                self.request.GET.get(REQUEST_KEY_SAML_SIGNATURE),
190                self.request.GET.get(REQUEST_KEY_SAML_SIG_ALG),
191            )
192            self.plan_context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] = auth_n_request
193        except CannotHandleAssertion as exc:
194            return self.saml_request_error(exc)
195        return None
196
197
198@method_decorator(xframe_options_sameorigin, name="dispatch")
199@method_decorator(csrf_exempt, name="dispatch")
200class SAMLSSOBindingPOSTView(SAMLSSOView):
201    """SAML Handler for SSO/POST bindings"""
202
203    def check_saml_request(self) -> HttpRequest | None:
204        """Handle POST bindings"""
205        payload = self.request.POST
206        # Restore the post body from the session
207        # This happens when using POST bindings but the user isn't logged in
208        # (user gets redirected and POST body is 'lost')
209        if SESSION_KEY_POST in self.request.session:
210            payload = self.request.session.pop(SESSION_KEY_POST)
211        if REQUEST_KEY_SAML_REQUEST not in payload:
212            LOGGER.info("SAML payload missing")
213            return bad_request_message(self.request, _("The SAML request payload is missing."))
214
215        try:
216            auth_n_request = AuthNRequestParser(self.provider).parse(
217                payload[REQUEST_KEY_SAML_REQUEST],
218                payload.get(REQUEST_KEY_RELAY_STATE),
219            )
220            self.plan_context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] = auth_n_request
221        except CannotHandleAssertion as exc:
222            return self.saml_request_error(exc)
223        return None
224
225
226class SAMLSSOBindingInitView(SAMLSSOView):
227    """SAML Handler for for IdP Initiated login flows"""
228
229    def check_saml_request(self) -> HttpRequest | None:
230        """Create SAML Response from scratch"""
231        LOGGER.debug("No SAML Request, using IdP-initiated flow.")
232        auth_n_request = AuthNRequestParser(self.provider).idp_initiated()
233        self.plan_context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] = auth_n_request
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
SESSION_KEY_LAST_LOGIN_UID = 'authentik/providers/saml/last_login_uid'
class SAMLSSOView(authentik.policies.views.PolicyAccessView):
 47class SAMLSSOView(PolicyAccessView):
 48    """SAML SSO Base View, which plans a flow and injects our final stage.
 49    Calls get/post handler."""
 50
 51    def __init__(self, **kwargs):
 52        super().__init__(**kwargs)
 53        self.plan_context = {}
 54
 55    def resolve_provider_application(self):
 56        self.application = get_object_or_404(Application, slug=self.kwargs["application_slug"])
 57        self.provider: SAMLProvider = get_object_or_404(
 58            SAMLProvider, pk=self.application.provider_id
 59        )
 60
 61    def continuous_login_hold_required(self) -> bool:
 62        """Conservatively hold tabs when authorization may require the flow executor.
 63
 64        Stage policies can depend on the user who is about to authenticate, so they cannot be
 65        evaluated accurately here. An entirely empty flow is the only flow known to be safe.
 66        """
 67        # TODO: Revisit once #27280 lands, which holds tabs behind a single auto-redirecting source.
 68        return FlowStageBinding.objects.filter(target=self.provider.authorization_flow).exists()
 69
 70    def check_saml_request(self) -> HttpRequest | None:
 71        """Handler to verify the SAML Request. Must be implemented by a subclass"""
 72        raise NotImplementedError
 73
 74    def saml_request_error(self, exc: CannotHandleAssertion) -> HttpResponse:
 75        """Record the full error for administrators and show the user only the safe message"""
 76        message = str(exc)
 77        context = {}
 78        if isinstance(exc.detail, Exception):
 79            context["exception"] = exception_to_dict(exc.detail)
 80        elif exc.detail:
 81            context["detail"] = str(exc.detail)
 82        Event.new(
 83            EventAction.CONFIGURATION_ERROR,
 84            provider=self.provider,
 85            message=message,
 86            **context,
 87        ).save()
 88        LOGGER.info(
 89            "Failed to process SAML request",
 90            provider=self.provider.name,
 91            message=message,
 92            detail=exc.detail,
 93        )
 94        return bad_request_message(self.request, message)
 95
 96    def get_resume_url(self) -> str | None:
 97        """URL to re-enter this SAML request after another tab authenticated."""
 98        return None
 99
100    def get(self, request: HttpRequest, application_slug: str) -> HttpResponse:
101        """Verify the SAML Request, and if valid initiate the FlowPlanner for the application"""
102        # Call the method handler, which checks the SAML
103        # Request and returns a HTTP Response on error
104        method_response = self.check_saml_request()
105        if method_response:
106            return method_response
107        # If the SP requested ForceAuthn, we must re-authenticate the user regardless of
108        # any existing session, mirroring the OIDC provider's prompt=login handling.
109        # The provider can be configured to ignore the attribute, in which case the
110        # existing session is used as if ForceAuthn had not been set.
111        auth_n_request: AuthNRequest | None = self.plan_context.get(
112            PLAN_CONTEXT_SAML_AUTH_N_REQUEST
113        )
114        if auth_n_request and auth_n_request.force_authn and not self.provider.ignore_force_authn:
115            reauth_response = self.check_force_authn(request)
116            if reauth_response:
117                return reauth_response
118        # Regardless, we start the planner and return to it
119        planner = FlowPlanner(self.provider.authorization_flow)
120        planner.allow_empty_flows = True
121        try:
122            plan = planner.plan(
123                request,
124                {
125                    PLAN_CONTEXT_SSO: True,
126                    PLAN_CONTEXT_APPLICATION: self.application,
127                    PLAN_CONTEXT_CONSENT_HEADER: _("You're about to sign into %(application)s.")
128                    % {"application": self.application.name},
129                    PLAN_CONTEXT_CONSENT_PERMISSIONS: [],
130                    **self.plan_context,
131                },
132            )
133        except FlowNonApplicableException:
134            raise Http404 from None
135        plan.append_stage(in_memory_stage(SAMLFlowFinalView))
136        return plan.to_redirect(
137            request,
138            self.provider.authorization_flow,
139            next=self.get_resume_url(),
140            allowed_silent_types=(
141                [SAMLFlowFinalView]
142                if self.provider.sp_binding in [SAMLBindings.POST, SAMLBindings.REDIRECT]
143                # Under continuous login, other tabs hold whenever the authorization flow has
144                # bound stages, and only the flow interface tells them when this tab is done.
145                and (not ContinuousLogin.get() or not self.continuous_login_hold_required())
146                else []
147            ),
148        )
149
150    def post(self, request: HttpRequest, application_slug: str) -> HttpResponse:
151        """GET and POST use the same handler, but we can't
152        override .dispatch easily because PolicyAccessView's dispatch"""
153        return self.get(request, application_slug)
154
155    def check_force_authn(self, request: HttpRequest) -> HttpResponse | None:
156        """Trigger re-authentication when the AuthnRequest carries ForceAuthn. Returns a
157        redirect into the authentication flow if re-auth is still required, otherwise
158        None to let the SSO flow proceed."""
159        login_event = get_login_event(request)
160        login_uid = str(login_event.pk) if login_event else None
161        # Re-authenticate if it hasn't happened yet: either we have no record of a forced
162        # login for this session, or the session's login event still matches the one we
163        # saw before redirecting to the authentication flow. Once the user re-logs in, a
164        # new login event is created, the UID changes, and we stop forcing re-auth.
165        if (
166            SESSION_KEY_LAST_LOGIN_UID not in request.session
167            or login_uid == request.session[SESSION_KEY_LAST_LOGIN_UID]
168        ):
169            request.session[SESSION_KEY_LAST_LOGIN_UID] = login_uid
170            return self.handle_no_permission()
171        return None

SAML SSO Base View, which plans a flow and injects our final stage. Calls get/post handler.

SAMLSSOView(**kwargs)
51    def __init__(self, **kwargs):
52        super().__init__(**kwargs)
53        self.plan_context = {}

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

plan_context
def resolve_provider_application(self):
55    def resolve_provider_application(self):
56        self.application = get_object_or_404(Application, slug=self.kwargs["application_slug"])
57        self.provider: SAMLProvider = get_object_or_404(
58            SAMLProvider, pk=self.application.provider_id
59        )

Resolve self.provider and self.application. *.DoesNotExist Exceptions cause a normal AccessDenied view to be shown. An Http404 exception is not caught, and will return directly

def continuous_login_hold_required(self) -> bool:
61    def continuous_login_hold_required(self) -> bool:
62        """Conservatively hold tabs when authorization may require the flow executor.
63
64        Stage policies can depend on the user who is about to authenticate, so they cannot be
65        evaluated accurately here. An entirely empty flow is the only flow known to be safe.
66        """
67        # TODO: Revisit once #27280 lands, which holds tabs behind a single auto-redirecting source.
68        return FlowStageBinding.objects.filter(target=self.provider.authorization_flow).exists()

Conservatively hold tabs when authorization may require the flow executor.

Stage policies can depend on the user who is about to authenticate, so they cannot be evaluated accurately here. An entirely empty flow is the only flow known to be safe.

def check_saml_request(self) -> django.http.request.HttpRequest | None:
70    def check_saml_request(self) -> HttpRequest | None:
71        """Handler to verify the SAML Request. Must be implemented by a subclass"""
72        raise NotImplementedError

Handler to verify the SAML Request. Must be implemented by a subclass

def saml_request_error( self, exc: authentik.common.saml.exceptions.CannotHandleAssertion) -> django.http.response.HttpResponse:
74    def saml_request_error(self, exc: CannotHandleAssertion) -> HttpResponse:
75        """Record the full error for administrators and show the user only the safe message"""
76        message = str(exc)
77        context = {}
78        if isinstance(exc.detail, Exception):
79            context["exception"] = exception_to_dict(exc.detail)
80        elif exc.detail:
81            context["detail"] = str(exc.detail)
82        Event.new(
83            EventAction.CONFIGURATION_ERROR,
84            provider=self.provider,
85            message=message,
86            **context,
87        ).save()
88        LOGGER.info(
89            "Failed to process SAML request",
90            provider=self.provider.name,
91            message=message,
92            detail=exc.detail,
93        )
94        return bad_request_message(self.request, message)

Record the full error for administrators and show the user only the safe message

def get_resume_url(self) -> str | None:
96    def get_resume_url(self) -> str | None:
97        """URL to re-enter this SAML request after another tab authenticated."""
98        return None

URL to re-enter this SAML request after another tab authenticated.

def get( self, request: django.http.request.HttpRequest, application_slug: str) -> django.http.response.HttpResponse:
100    def get(self, request: HttpRequest, application_slug: str) -> HttpResponse:
101        """Verify the SAML Request, and if valid initiate the FlowPlanner for the application"""
102        # Call the method handler, which checks the SAML
103        # Request and returns a HTTP Response on error
104        method_response = self.check_saml_request()
105        if method_response:
106            return method_response
107        # If the SP requested ForceAuthn, we must re-authenticate the user regardless of
108        # any existing session, mirroring the OIDC provider's prompt=login handling.
109        # The provider can be configured to ignore the attribute, in which case the
110        # existing session is used as if ForceAuthn had not been set.
111        auth_n_request: AuthNRequest | None = self.plan_context.get(
112            PLAN_CONTEXT_SAML_AUTH_N_REQUEST
113        )
114        if auth_n_request and auth_n_request.force_authn and not self.provider.ignore_force_authn:
115            reauth_response = self.check_force_authn(request)
116            if reauth_response:
117                return reauth_response
118        # Regardless, we start the planner and return to it
119        planner = FlowPlanner(self.provider.authorization_flow)
120        planner.allow_empty_flows = True
121        try:
122            plan = planner.plan(
123                request,
124                {
125                    PLAN_CONTEXT_SSO: True,
126                    PLAN_CONTEXT_APPLICATION: self.application,
127                    PLAN_CONTEXT_CONSENT_HEADER: _("You're about to sign into %(application)s.")
128                    % {"application": self.application.name},
129                    PLAN_CONTEXT_CONSENT_PERMISSIONS: [],
130                    **self.plan_context,
131                },
132            )
133        except FlowNonApplicableException:
134            raise Http404 from None
135        plan.append_stage(in_memory_stage(SAMLFlowFinalView))
136        return plan.to_redirect(
137            request,
138            self.provider.authorization_flow,
139            next=self.get_resume_url(),
140            allowed_silent_types=(
141                [SAMLFlowFinalView]
142                if self.provider.sp_binding in [SAMLBindings.POST, SAMLBindings.REDIRECT]
143                # Under continuous login, other tabs hold whenever the authorization flow has
144                # bound stages, and only the flow interface tells them when this tab is done.
145                and (not ContinuousLogin.get() or not self.continuous_login_hold_required())
146                else []
147            ),
148        )

Verify the SAML Request, and if valid initiate the FlowPlanner for the application

def post( self, request: django.http.request.HttpRequest, application_slug: str) -> django.http.response.HttpResponse:
150    def post(self, request: HttpRequest, application_slug: str) -> HttpResponse:
151        """GET and POST use the same handler, but we can't
152        override .dispatch easily because PolicyAccessView's dispatch"""
153        return self.get(request, application_slug)

GET and POST use the same handler, but we can't override .dispatch easily because PolicyAccessView's dispatch

def check_force_authn( self, request: django.http.request.HttpRequest) -> django.http.response.HttpResponse | None:
155    def check_force_authn(self, request: HttpRequest) -> HttpResponse | None:
156        """Trigger re-authentication when the AuthnRequest carries ForceAuthn. Returns a
157        redirect into the authentication flow if re-auth is still required, otherwise
158        None to let the SSO flow proceed."""
159        login_event = get_login_event(request)
160        login_uid = str(login_event.pk) if login_event else None
161        # Re-authenticate if it hasn't happened yet: either we have no record of a forced
162        # login for this session, or the session's login event still matches the one we
163        # saw before redirecting to the authentication flow. Once the user re-logs in, a
164        # new login event is created, the UID changes, and we stop forcing re-auth.
165        if (
166            SESSION_KEY_LAST_LOGIN_UID not in request.session
167            or login_uid == request.session[SESSION_KEY_LAST_LOGIN_UID]
168        ):
169            request.session[SESSION_KEY_LAST_LOGIN_UID] = login_uid
170            return self.handle_no_permission()
171        return None

Trigger re-authentication when the AuthnRequest carries ForceAuthn. Returns a redirect into the authentication flow if re-auth is still required, otherwise None to let the SSO flow proceed.

class SAMLSSOBindingRedirectView(SAMLSSOView):
174class SAMLSSOBindingRedirectView(SAMLSSOView):
175    """SAML Handler for SSO/Redirect bindings, which are sent via GET"""
176
177    def get_resume_url(self) -> str | None:
178        return self.request.get_full_path()
179
180    def check_saml_request(self) -> HttpRequest | None:
181        """Handle REDIRECT bindings"""
182        if REQUEST_KEY_SAML_REQUEST not in self.request.GET:
183            LOGGER.info("SAML payload missing")
184            return bad_request_message(self.request, _("The SAML request payload is missing."))
185
186        try:
187            auth_n_request = AuthNRequestParser(self.provider).parse_detached(
188                self.request.GET[REQUEST_KEY_SAML_REQUEST],
189                self.request.GET.get(REQUEST_KEY_RELAY_STATE),
190                self.request.GET.get(REQUEST_KEY_SAML_SIGNATURE),
191                self.request.GET.get(REQUEST_KEY_SAML_SIG_ALG),
192            )
193            self.plan_context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] = auth_n_request
194        except CannotHandleAssertion as exc:
195            return self.saml_request_error(exc)
196        return None

SAML Handler for SSO/Redirect bindings, which are sent via GET

def get_resume_url(self) -> str | None:
177    def get_resume_url(self) -> str | None:
178        return self.request.get_full_path()

URL to re-enter this SAML request after another tab authenticated.

def check_saml_request(self) -> django.http.request.HttpRequest | None:
180    def check_saml_request(self) -> HttpRequest | None:
181        """Handle REDIRECT bindings"""
182        if REQUEST_KEY_SAML_REQUEST not in self.request.GET:
183            LOGGER.info("SAML payload missing")
184            return bad_request_message(self.request, _("The SAML request payload is missing."))
185
186        try:
187            auth_n_request = AuthNRequestParser(self.provider).parse_detached(
188                self.request.GET[REQUEST_KEY_SAML_REQUEST],
189                self.request.GET.get(REQUEST_KEY_RELAY_STATE),
190                self.request.GET.get(REQUEST_KEY_SAML_SIGNATURE),
191                self.request.GET.get(REQUEST_KEY_SAML_SIG_ALG),
192            )
193            self.plan_context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] = auth_n_request
194        except CannotHandleAssertion as exc:
195            return self.saml_request_error(exc)
196        return None

Handle REDIRECT bindings

@method_decorator(xframe_options_sameorigin, name='dispatch')
@method_decorator(csrf_exempt, name='dispatch')
class SAMLSSOBindingPOSTView(SAMLSSOView):
199@method_decorator(xframe_options_sameorigin, name="dispatch")
200@method_decorator(csrf_exempt, name="dispatch")
201class SAMLSSOBindingPOSTView(SAMLSSOView):
202    """SAML Handler for SSO/POST bindings"""
203
204    def check_saml_request(self) -> HttpRequest | None:
205        """Handle POST bindings"""
206        payload = self.request.POST
207        # Restore the post body from the session
208        # This happens when using POST bindings but the user isn't logged in
209        # (user gets redirected and POST body is 'lost')
210        if SESSION_KEY_POST in self.request.session:
211            payload = self.request.session.pop(SESSION_KEY_POST)
212        if REQUEST_KEY_SAML_REQUEST not in payload:
213            LOGGER.info("SAML payload missing")
214            return bad_request_message(self.request, _("The SAML request payload is missing."))
215
216        try:
217            auth_n_request = AuthNRequestParser(self.provider).parse(
218                payload[REQUEST_KEY_SAML_REQUEST],
219                payload.get(REQUEST_KEY_RELAY_STATE),
220            )
221            self.plan_context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] = auth_n_request
222        except CannotHandleAssertion as exc:
223            return self.saml_request_error(exc)
224        return None

SAML Handler for SSO/POST bindings

def check_saml_request(self) -> django.http.request.HttpRequest | None:
204    def check_saml_request(self) -> HttpRequest | None:
205        """Handle POST bindings"""
206        payload = self.request.POST
207        # Restore the post body from the session
208        # This happens when using POST bindings but the user isn't logged in
209        # (user gets redirected and POST body is 'lost')
210        if SESSION_KEY_POST in self.request.session:
211            payload = self.request.session.pop(SESSION_KEY_POST)
212        if REQUEST_KEY_SAML_REQUEST not in payload:
213            LOGGER.info("SAML payload missing")
214            return bad_request_message(self.request, _("The SAML request payload is missing."))
215
216        try:
217            auth_n_request = AuthNRequestParser(self.provider).parse(
218                payload[REQUEST_KEY_SAML_REQUEST],
219                payload.get(REQUEST_KEY_RELAY_STATE),
220            )
221            self.plan_context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] = auth_n_request
222        except CannotHandleAssertion as exc:
223            return self.saml_request_error(exc)
224        return None

Handle POST bindings

def dispatch( self, request: django.http.request.HttpRequest, *args: Any, **kwargs: Any) -> django.http.response.HttpResponse:
68    def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
69        try:
70            self.pre_permission_check()
71        except RequestValidationError as exc:
72            if exc.response:
73                return exc.response
74            return self.handle_no_permission()
75        try:
76            self.resolve_provider_application()
77        except (Application.DoesNotExist, Provider.DoesNotExist) as exc:
78            LOGGER.warning("failed to resolve application", exc=exc)
79            return self.handle_no_permission_authenticated(
80                PolicyResult(False, _("Failed to resolve application"))
81            )
82        # Check if user is unauthenticated, so we pass the application
83        # for the identification stage
84        if not request.user.is_authenticated:
85            return self.handle_no_permission()
86        # Check permissions
87        result = self.user_has_access()
88        if not result.passing:
89            return self.handle_no_permission_authenticated(result)
90        return super().dispatch(request, *args, **kwargs)
class SAMLSSOBindingInitView(SAMLSSOView):
227class SAMLSSOBindingInitView(SAMLSSOView):
228    """SAML Handler for for IdP Initiated login flows"""
229
230    def check_saml_request(self) -> HttpRequest | None:
231        """Create SAML Response from scratch"""
232        LOGGER.debug("No SAML Request, using IdP-initiated flow.")
233        auth_n_request = AuthNRequestParser(self.provider).idp_initiated()
234        self.plan_context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] = auth_n_request

SAML Handler for for IdP Initiated login flows

def check_saml_request(self) -> django.http.request.HttpRequest | None:
230    def check_saml_request(self) -> HttpRequest | None:
231        """Create SAML Response from scratch"""
232        LOGGER.debug("No SAML Request, using IdP-initiated flow.")
233        auth_n_request = AuthNRequestParser(self.provider).idp_initiated()
234        self.plan_context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] = auth_n_request

Create SAML Response from scratch