authentik.sources.saml.views

saml sp views

  1"""saml sp views"""
  2
  3from urllib.parse import parse_qsl, urlparse, urlunparse
  4
  5from django.contrib.auth import logout
  6from django.contrib.auth.mixins import LoginRequiredMixin
  7from django.core.exceptions import SuspiciousOperation
  8from django.http import Http404, HttpRequest, HttpResponse
  9from django.http.response import HttpResponseBadRequest
 10from django.shortcuts import get_object_or_404, redirect
 11from django.utils.decorators import method_decorator
 12from django.utils.http import urlencode
 13from django.utils.translation import gettext as _
 14from django.views import View
 15from django.views.decorators.csrf import csrf_exempt
 16from structlog.stdlib import get_logger
 17from xmlsec import InternalError, VerificationError
 18
 19from authentik.flows.challenge import (
 20    PLAN_CONTEXT_ATTRS,
 21    PLAN_CONTEXT_TITLE,
 22    PLAN_CONTEXT_URL,
 23    AutosubmitChallenge,
 24    Challenge,
 25    ChallengeResponse,
 26)
 27from authentik.flows.exceptions import FlowNonApplicableException
 28from authentik.flows.models import in_memory_stage
 29from authentik.flows.planner import (
 30    PLAN_CONTEXT_REDIRECT,
 31    PLAN_CONTEXT_SOURCE,
 32    PLAN_CONTEXT_SSO,
 33    FlowPlan,
 34    FlowPlanner,
 35)
 36from authentik.flows.stage import ChallengeStageView
 37from authentik.flows.views.executor import NEXT_ARG_NAME, SESSION_KEY_GET, SESSION_KEY_PLAN
 38from authentik.lib.views import bad_request_message
 39from authentik.providers.saml.utils.encoding import nice64
 40from authentik.sources.saml.exceptions import SAMLException
 41from authentik.sources.saml.models import SAMLBindingTypes, SAMLSource
 42from authentik.sources.saml.processors.metadata import MetadataProcessor
 43from authentik.sources.saml.processors.request import RequestProcessor
 44from authentik.sources.saml.processors.response import ResponseProcessor
 45from authentik.stages.consent.stage import PLAN_CONTEXT_CONSENT_HEADER, ConsentStageView
 46
 47LOGGER = get_logger()
 48
 49
 50class AutosubmitStageView(ChallengeStageView):
 51    """Wrapper stage to create an autosubmit challenge from plan context variables"""
 52
 53    def get_challenge(self, *args, **kwargs) -> Challenge:
 54        return AutosubmitChallenge(
 55            data={
 56                "component": "ak-stage-autosubmit",
 57                "title": self.executor.plan.context.get(PLAN_CONTEXT_TITLE, ""),
 58                "url": self.executor.plan.context.get(PLAN_CONTEXT_URL, ""),
 59                "attrs": self.executor.plan.context.get(PLAN_CONTEXT_ATTRS, ""),
 60            },
 61        )
 62
 63    # Since `ak-stage-autosubmit` redirects off site, we don't have anything to check
 64    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
 65        return HttpResponseBadRequest()
 66
 67
 68class InitiateView(View):
 69    """Get the Form with SAML Request, which sends us to the IDP"""
 70
 71    def handle_login_flow(self, source: SAMLSource, *stages_to_append, **kwargs) -> HttpResponse:
 72        """Prepare Authentication Plan, redirect user FlowExecutor"""
 73        # Ensure redirect is carried through when user was trying to
 74        # authorize application
 75        final_redirect = self.request.session.get(SESSION_KEY_GET, {}).get(
 76            NEXT_ARG_NAME, "authentik_core:if-user"
 77        )
 78        kwargs.update(
 79            {
 80                PLAN_CONTEXT_SSO: True,
 81                PLAN_CONTEXT_SOURCE: source,
 82                PLAN_CONTEXT_REDIRECT: final_redirect,
 83            }
 84        )
 85        # We run the Flow planner here so we can pass the Pending user in the context
 86        planner = FlowPlanner(source.pre_authentication_flow)
 87        planner.allow_empty_flows = True
 88        try:
 89            plan = planner.plan(self.request, kwargs)
 90        except FlowNonApplicableException:
 91            raise Http404 from None
 92        for stage in stages_to_append:
 93            plan.append_stage(stage)
 94        return plan.to_redirect(self.request, source.pre_authentication_flow)
 95
 96    def get(self, request: HttpRequest, source_slug: str) -> HttpResponse:
 97        """Replies with an XHTML SSO Request."""
 98        source: SAMLSource = get_object_or_404(SAMLSource, slug=source_slug)
 99        if not source.enabled:
100            raise Http404
101        relay_state = request.GET.get("next", "")
102        auth_n_req = RequestProcessor(source, request, relay_state)
103        # If the source is configured for Redirect bindings, we can just redirect there
104        if source.binding_type == SAMLBindingTypes.REDIRECT:
105            # Parse the initial SSO URL
106            sso_url = urlparse(source.sso_url)
107            # Parse the querystring into a dict...
108            url_kwargs = dict(parse_qsl(sso_url.query))
109            # ... and update it with the SAML args
110            url_kwargs.update(auth_n_req.build_auth_n_detached())
111            # Update the url
112            final_url = urlunparse(sso_url._replace(query=urlencode(url_kwargs)))
113            return redirect(final_url)
114        # As POST Binding we show a form
115        try:
116            saml_request = nice64(auth_n_req.build_auth_n())
117        except InternalError as exc:
118            LOGGER.warning("Failed to build SAML request", source=source.slug, exc=exc)
119            return bad_request_message(request, _("Failed to build the SAML request."))
120        injected_stages = []
121        plan_kwargs = {
122            PLAN_CONTEXT_TITLE: f"Redirecting to {source.name}...",
123            PLAN_CONTEXT_ATTRS: {
124                "SAMLRequest": saml_request,
125                "RelayState": relay_state,
126            },
127            PLAN_CONTEXT_URL: source.sso_url,
128        }
129        # For just POST we add a consent stage,
130        # otherwise we default to POST_AUTO, with direct redirect
131        if source.binding_type == SAMLBindingTypes.POST:
132            injected_stages.append(in_memory_stage(ConsentStageView))
133            plan_kwargs[PLAN_CONTEXT_CONSENT_HEADER] = _("Continue to {source_name}").format(
134                source_name=source.name
135            )
136        injected_stages.append(in_memory_stage(AutosubmitStageView))
137        return self.handle_login_flow(
138            source,
139            *injected_stages,
140            **plan_kwargs,
141        )
142
143
144@method_decorator(csrf_exempt, name="dispatch")
145class ACSView(View):
146    """AssertionConsumerService, consume assertion and log user in"""
147
148    def error_response(self, source: SAMLSource, exc: Exception) -> HttpResponse:
149        """Log the full error for administrators and show the user a generic message"""
150        LOGGER.warning("Failed to process SAML response", source=source.slug, exc=exc)
151        if isinstance(exc, SAMLException):
152            message = exc.default_message
153        else:
154            message = _("Failed to process the SAML response.")
155        return bad_request_message(self.request, message)
156
157    def post(self, request: HttpRequest, source_slug: str) -> HttpResponse:
158        """Handles a POSTed SSO Assertion and logs the user in."""
159        source: SAMLSource = get_object_or_404(SAMLSource, slug=source_slug)
160        if not source.enabled:
161            raise Http404
162        processor = ResponseProcessor(source, request)
163        try:
164            processor.parse()
165        except (
166            SAMLException,
167            SuspiciousOperation,
168            VerificationError,
169            ValueError,
170        ) as exc:
171            return self.error_response(source, exc)
172
173        try:
174            if SESSION_KEY_PLAN in request.session:
175                plan: FlowPlan = self.request.session[SESSION_KEY_PLAN]
176                plan_redirect = plan.context.get(PLAN_CONTEXT_REDIRECT)
177                if plan_redirect:
178                    self.request.session[SESSION_KEY_GET] = {NEXT_ARG_NAME: plan_redirect}
179            return processor.prepare_flow_manager().get_flow()
180        except (SAMLException, ValueError) as exc:
181            return self.error_response(source, exc)
182
183
184class SLOView(LoginRequiredMixin, View):
185    """Single-Logout-View"""
186
187    def dispatch(self, request: HttpRequest, source_slug: str) -> HttpResponse:
188        """Log user out and redirect them to the IdP's SLO URL."""
189        source: SAMLSource = get_object_or_404(SAMLSource, slug=source_slug)
190        if not source.enabled:
191            raise Http404
192        logout(request)
193        return redirect(source.slo_url)
194
195
196class MetadataView(View):
197    """Return XML Metadata for IDP"""
198
199    def dispatch(self, request: HttpRequest, source_slug: str) -> HttpResponse:
200        """Replies with the XML Metadata SPSSODescriptor."""
201        source: SAMLSource = get_object_or_404(SAMLSource, slug=source_slug)
202        metadata = MetadataProcessor(source, request).build_entity_descriptor()
203        return HttpResponse(metadata, content_type="text/xml")
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
class AutosubmitStageView(authentik.flows.stage.ChallengeStageView):
51class AutosubmitStageView(ChallengeStageView):
52    """Wrapper stage to create an autosubmit challenge from plan context variables"""
53
54    def get_challenge(self, *args, **kwargs) -> Challenge:
55        return AutosubmitChallenge(
56            data={
57                "component": "ak-stage-autosubmit",
58                "title": self.executor.plan.context.get(PLAN_CONTEXT_TITLE, ""),
59                "url": self.executor.plan.context.get(PLAN_CONTEXT_URL, ""),
60                "attrs": self.executor.plan.context.get(PLAN_CONTEXT_ATTRS, ""),
61            },
62        )
63
64    # Since `ak-stage-autosubmit` redirects off site, we don't have anything to check
65    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
66        return HttpResponseBadRequest()

Wrapper stage to create an autosubmit challenge from plan context variables

def get_challenge(self, *args, **kwargs) -> authentik.flows.challenge.Challenge:
54    def get_challenge(self, *args, **kwargs) -> Challenge:
55        return AutosubmitChallenge(
56            data={
57                "component": "ak-stage-autosubmit",
58                "title": self.executor.plan.context.get(PLAN_CONTEXT_TITLE, ""),
59                "url": self.executor.plan.context.get(PLAN_CONTEXT_URL, ""),
60                "attrs": self.executor.plan.context.get(PLAN_CONTEXT_ATTRS, ""),
61            },
62        )

Return the challenge that the client should solve

def challenge_valid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
65    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
66        return HttpResponseBadRequest()

Callback when the challenge has the correct format

class InitiateView(django.views.generic.base.View):
 69class InitiateView(View):
 70    """Get the Form with SAML Request, which sends us to the IDP"""
 71
 72    def handle_login_flow(self, source: SAMLSource, *stages_to_append, **kwargs) -> HttpResponse:
 73        """Prepare Authentication Plan, redirect user FlowExecutor"""
 74        # Ensure redirect is carried through when user was trying to
 75        # authorize application
 76        final_redirect = self.request.session.get(SESSION_KEY_GET, {}).get(
 77            NEXT_ARG_NAME, "authentik_core:if-user"
 78        )
 79        kwargs.update(
 80            {
 81                PLAN_CONTEXT_SSO: True,
 82                PLAN_CONTEXT_SOURCE: source,
 83                PLAN_CONTEXT_REDIRECT: final_redirect,
 84            }
 85        )
 86        # We run the Flow planner here so we can pass the Pending user in the context
 87        planner = FlowPlanner(source.pre_authentication_flow)
 88        planner.allow_empty_flows = True
 89        try:
 90            plan = planner.plan(self.request, kwargs)
 91        except FlowNonApplicableException:
 92            raise Http404 from None
 93        for stage in stages_to_append:
 94            plan.append_stage(stage)
 95        return plan.to_redirect(self.request, source.pre_authentication_flow)
 96
 97    def get(self, request: HttpRequest, source_slug: str) -> HttpResponse:
 98        """Replies with an XHTML SSO Request."""
 99        source: SAMLSource = get_object_or_404(SAMLSource, slug=source_slug)
100        if not source.enabled:
101            raise Http404
102        relay_state = request.GET.get("next", "")
103        auth_n_req = RequestProcessor(source, request, relay_state)
104        # If the source is configured for Redirect bindings, we can just redirect there
105        if source.binding_type == SAMLBindingTypes.REDIRECT:
106            # Parse the initial SSO URL
107            sso_url = urlparse(source.sso_url)
108            # Parse the querystring into a dict...
109            url_kwargs = dict(parse_qsl(sso_url.query))
110            # ... and update it with the SAML args
111            url_kwargs.update(auth_n_req.build_auth_n_detached())
112            # Update the url
113            final_url = urlunparse(sso_url._replace(query=urlencode(url_kwargs)))
114            return redirect(final_url)
115        # As POST Binding we show a form
116        try:
117            saml_request = nice64(auth_n_req.build_auth_n())
118        except InternalError as exc:
119            LOGGER.warning("Failed to build SAML request", source=source.slug, exc=exc)
120            return bad_request_message(request, _("Failed to build the SAML request."))
121        injected_stages = []
122        plan_kwargs = {
123            PLAN_CONTEXT_TITLE: f"Redirecting to {source.name}...",
124            PLAN_CONTEXT_ATTRS: {
125                "SAMLRequest": saml_request,
126                "RelayState": relay_state,
127            },
128            PLAN_CONTEXT_URL: source.sso_url,
129        }
130        # For just POST we add a consent stage,
131        # otherwise we default to POST_AUTO, with direct redirect
132        if source.binding_type == SAMLBindingTypes.POST:
133            injected_stages.append(in_memory_stage(ConsentStageView))
134            plan_kwargs[PLAN_CONTEXT_CONSENT_HEADER] = _("Continue to {source_name}").format(
135                source_name=source.name
136            )
137        injected_stages.append(in_memory_stage(AutosubmitStageView))
138        return self.handle_login_flow(
139            source,
140            *injected_stages,
141            **plan_kwargs,
142        )

Get the Form with SAML Request, which sends us to the IDP

def handle_login_flow( self, source: authentik.sources.saml.models.SAMLSource, *stages_to_append, **kwargs) -> django.http.response.HttpResponse:
72    def handle_login_flow(self, source: SAMLSource, *stages_to_append, **kwargs) -> HttpResponse:
73        """Prepare Authentication Plan, redirect user FlowExecutor"""
74        # Ensure redirect is carried through when user was trying to
75        # authorize application
76        final_redirect = self.request.session.get(SESSION_KEY_GET, {}).get(
77            NEXT_ARG_NAME, "authentik_core:if-user"
78        )
79        kwargs.update(
80            {
81                PLAN_CONTEXT_SSO: True,
82                PLAN_CONTEXT_SOURCE: source,
83                PLAN_CONTEXT_REDIRECT: final_redirect,
84            }
85        )
86        # We run the Flow planner here so we can pass the Pending user in the context
87        planner = FlowPlanner(source.pre_authentication_flow)
88        planner.allow_empty_flows = True
89        try:
90            plan = planner.plan(self.request, kwargs)
91        except FlowNonApplicableException:
92            raise Http404 from None
93        for stage in stages_to_append:
94            plan.append_stage(stage)
95        return plan.to_redirect(self.request, source.pre_authentication_flow)

Prepare Authentication Plan, redirect user FlowExecutor

def get( self, request: django.http.request.HttpRequest, source_slug: str) -> django.http.response.HttpResponse:
 97    def get(self, request: HttpRequest, source_slug: str) -> HttpResponse:
 98        """Replies with an XHTML SSO Request."""
 99        source: SAMLSource = get_object_or_404(SAMLSource, slug=source_slug)
100        if not source.enabled:
101            raise Http404
102        relay_state = request.GET.get("next", "")
103        auth_n_req = RequestProcessor(source, request, relay_state)
104        # If the source is configured for Redirect bindings, we can just redirect there
105        if source.binding_type == SAMLBindingTypes.REDIRECT:
106            # Parse the initial SSO URL
107            sso_url = urlparse(source.sso_url)
108            # Parse the querystring into a dict...
109            url_kwargs = dict(parse_qsl(sso_url.query))
110            # ... and update it with the SAML args
111            url_kwargs.update(auth_n_req.build_auth_n_detached())
112            # Update the url
113            final_url = urlunparse(sso_url._replace(query=urlencode(url_kwargs)))
114            return redirect(final_url)
115        # As POST Binding we show a form
116        try:
117            saml_request = nice64(auth_n_req.build_auth_n())
118        except InternalError as exc:
119            LOGGER.warning("Failed to build SAML request", source=source.slug, exc=exc)
120            return bad_request_message(request, _("Failed to build the SAML request."))
121        injected_stages = []
122        plan_kwargs = {
123            PLAN_CONTEXT_TITLE: f"Redirecting to {source.name}...",
124            PLAN_CONTEXT_ATTRS: {
125                "SAMLRequest": saml_request,
126                "RelayState": relay_state,
127            },
128            PLAN_CONTEXT_URL: source.sso_url,
129        }
130        # For just POST we add a consent stage,
131        # otherwise we default to POST_AUTO, with direct redirect
132        if source.binding_type == SAMLBindingTypes.POST:
133            injected_stages.append(in_memory_stage(ConsentStageView))
134            plan_kwargs[PLAN_CONTEXT_CONSENT_HEADER] = _("Continue to {source_name}").format(
135                source_name=source.name
136            )
137        injected_stages.append(in_memory_stage(AutosubmitStageView))
138        return self.handle_login_flow(
139            source,
140            *injected_stages,
141            **plan_kwargs,
142        )

Replies with an XHTML SSO Request.

@method_decorator(csrf_exempt, name='dispatch')
class ACSView(django.views.generic.base.View):
145@method_decorator(csrf_exempt, name="dispatch")
146class ACSView(View):
147    """AssertionConsumerService, consume assertion and log user in"""
148
149    def error_response(self, source: SAMLSource, exc: Exception) -> HttpResponse:
150        """Log the full error for administrators and show the user a generic message"""
151        LOGGER.warning("Failed to process SAML response", source=source.slug, exc=exc)
152        if isinstance(exc, SAMLException):
153            message = exc.default_message
154        else:
155            message = _("Failed to process the SAML response.")
156        return bad_request_message(self.request, message)
157
158    def post(self, request: HttpRequest, source_slug: str) -> HttpResponse:
159        """Handles a POSTed SSO Assertion and logs the user in."""
160        source: SAMLSource = get_object_or_404(SAMLSource, slug=source_slug)
161        if not source.enabled:
162            raise Http404
163        processor = ResponseProcessor(source, request)
164        try:
165            processor.parse()
166        except (
167            SAMLException,
168            SuspiciousOperation,
169            VerificationError,
170            ValueError,
171        ) as exc:
172            return self.error_response(source, exc)
173
174        try:
175            if SESSION_KEY_PLAN in request.session:
176                plan: FlowPlan = self.request.session[SESSION_KEY_PLAN]
177                plan_redirect = plan.context.get(PLAN_CONTEXT_REDIRECT)
178                if plan_redirect:
179                    self.request.session[SESSION_KEY_GET] = {NEXT_ARG_NAME: plan_redirect}
180            return processor.prepare_flow_manager().get_flow()
181        except (SAMLException, ValueError) as exc:
182            return self.error_response(source, exc)

AssertionConsumerService, consume assertion and log user in

def error_response( self, source: authentik.sources.saml.models.SAMLSource, exc: Exception) -> django.http.response.HttpResponse:
149    def error_response(self, source: SAMLSource, exc: Exception) -> HttpResponse:
150        """Log the full error for administrators and show the user a generic message"""
151        LOGGER.warning("Failed to process SAML response", source=source.slug, exc=exc)
152        if isinstance(exc, SAMLException):
153            message = exc.default_message
154        else:
155            message = _("Failed to process the SAML response.")
156        return bad_request_message(self.request, message)

Log the full error for administrators and show the user a generic message

def post( self, request: django.http.request.HttpRequest, source_slug: str) -> django.http.response.HttpResponse:
158    def post(self, request: HttpRequest, source_slug: str) -> HttpResponse:
159        """Handles a POSTed SSO Assertion and logs the user in."""
160        source: SAMLSource = get_object_or_404(SAMLSource, slug=source_slug)
161        if not source.enabled:
162            raise Http404
163        processor = ResponseProcessor(source, request)
164        try:
165            processor.parse()
166        except (
167            SAMLException,
168            SuspiciousOperation,
169            VerificationError,
170            ValueError,
171        ) as exc:
172            return self.error_response(source, exc)
173
174        try:
175            if SESSION_KEY_PLAN in request.session:
176                plan: FlowPlan = self.request.session[SESSION_KEY_PLAN]
177                plan_redirect = plan.context.get(PLAN_CONTEXT_REDIRECT)
178                if plan_redirect:
179                    self.request.session[SESSION_KEY_GET] = {NEXT_ARG_NAME: plan_redirect}
180            return processor.prepare_flow_manager().get_flow()
181        except (SAMLException, ValueError) as exc:
182            return self.error_response(source, exc)

Handles a POSTed SSO Assertion and logs the user in.

def dispatch(self, request, *args, **kwargs):
135    def dispatch(self, request, *args, **kwargs):
136        # Try to dispatch to the right method; if a method doesn't exist,
137        # defer to the error handler. Also defer to the error handler if the
138        # request method isn't on the approved list.
139        if request.method.lower() in self.http_method_names:
140            handler = getattr(
141                self, request.method.lower(), self.http_method_not_allowed
142            )
143        else:
144            handler = self.http_method_not_allowed
145        return handler(request, *args, **kwargs)
class SLOView(django.contrib.auth.mixins.LoginRequiredMixin, django.views.generic.base.View):
185class SLOView(LoginRequiredMixin, View):
186    """Single-Logout-View"""
187
188    def dispatch(self, request: HttpRequest, source_slug: str) -> HttpResponse:
189        """Log user out and redirect them to the IdP's SLO URL."""
190        source: SAMLSource = get_object_or_404(SAMLSource, slug=source_slug)
191        if not source.enabled:
192            raise Http404
193        logout(request)
194        return redirect(source.slo_url)

Single-Logout-View

def dispatch( self, request: django.http.request.HttpRequest, source_slug: str) -> django.http.response.HttpResponse:
188    def dispatch(self, request: HttpRequest, source_slug: str) -> HttpResponse:
189        """Log user out and redirect them to the IdP's SLO URL."""
190        source: SAMLSource = get_object_or_404(SAMLSource, slug=source_slug)
191        if not source.enabled:
192            raise Http404
193        logout(request)
194        return redirect(source.slo_url)

Log user out and redirect them to the IdP's SLO URL.

class MetadataView(django.views.generic.base.View):
197class MetadataView(View):
198    """Return XML Metadata for IDP"""
199
200    def dispatch(self, request: HttpRequest, source_slug: str) -> HttpResponse:
201        """Replies with the XML Metadata SPSSODescriptor."""
202        source: SAMLSource = get_object_or_404(SAMLSource, slug=source_slug)
203        metadata = MetadataProcessor(source, request).build_entity_descriptor()
204        return HttpResponse(metadata, content_type="text/xml")

Return XML Metadata for IDP

def dispatch( self, request: django.http.request.HttpRequest, source_slug: str) -> django.http.response.HttpResponse:
200    def dispatch(self, request: HttpRequest, source_slug: str) -> HttpResponse:
201        """Replies with the XML Metadata SPSSODescriptor."""
202        source: SAMLSource = get_object_or_404(SAMLSource, slug=source_slug)
203        metadata = MetadataProcessor(source, request).build_entity_descriptor()
204        return HttpResponse(metadata, content_type="text/xml")

Replies with the XML Metadata SPSSODescriptor.