authentik.providers.saml.views.flows
authentik SAML IDP Views
1"""authentik SAML IDP Views""" 2 3from django.core.validators import URLValidator 4from django.http import HttpRequest, HttpResponse 5from django.http.response import HttpResponseBadRequest 6from django.shortcuts import get_object_or_404, redirect 7from django.template.response import TemplateResponse 8from django.utils.cache import add_never_cache_headers 9from django.utils.http import urlencode 10from django.utils.translation import gettext as _ 11from structlog.stdlib import get_logger 12 13from authentik.core.models import Application, AuthenticatedSession 14from authentik.events.models import Event, EventAction 15from authentik.flows.apps import ContinuousLogin 16from authentik.flows.challenge import ( 17 PLAN_CONTEXT_TITLE, 18 AutosubmitChallenge, 19 AutoSubmitChallengeResponse, 20 Challenge, 21 ChallengeResponse, 22 HttpChallengeResponse, 23 RedirectChallenge, 24) 25from authentik.flows.planner import PLAN_CONTEXT_APPLICATION 26from authentik.flows.stage import ChallengeStageView 27from authentik.lib.views import bad_request_message 28from authentik.policies.utils import delete_none_values 29from authentik.providers.saml.models import SAMLBindings, SAMLProvider, SAMLSession 30from authentik.providers.saml.processors.assertion import AssertionProcessor 31from authentik.providers.saml.processors.authn_request_parser import AuthNRequest 32from authentik.providers.saml.utils.encoding import deflate_and_base64_encode, nice64 33from authentik.sources.saml.exceptions import SAMLException 34 35LOGGER = get_logger() 36URL_VALIDATOR = URLValidator(schemes=("http", "https")) 37REQUEST_KEY_SAML_REQUEST = "SAMLRequest" 38REQUEST_KEY_SAML_SIGNATURE = "Signature" 39REQUEST_KEY_SAML_SIG_ALG = "SigAlg" 40REQUEST_KEY_SAML_RESPONSE = "SAMLResponse" 41REQUEST_KEY_RELAY_STATE = "RelayState" 42 43DEPRECATION_SP_BINDING_REDIRECT = "authentik.providers.saml.sp_binding_redirect" 44 45PLAN_CONTEXT_SAML_AUTH_N_REQUEST = "authentik/providers/saml/authn_request" 46PLAN_CONTEXT_SAML_LOGOUT_REQUEST = "authentik/providers/saml/logout_request" 47PLAN_CONTEXT_SAML_LOGOUT_NATIVE_SESSIONS = "goauthentik.io/providers/saml/native_sessions" 48PLAN_CONTEXT_SAML_LOGOUT_IFRAME_SESSIONS = "goauthentik.io/providers/saml/iframe_sessions" 49PLAN_CONTEXT_SAML_RELAY_STATE = "goauthentik.io/providers/saml/relay_state" 50 51 52# This View doesn't have a URL on purpose, as its called by the FlowExecutor 53class SAMLFlowFinalView(ChallengeStageView): 54 """View used by FlowExecutor after all stages have passed. Logs the authorization, 55 and redirects to the SP (if REDIRECT is configured) or shows an auto-submit element 56 (if POST is configured).""" 57 58 response_class = AutoSubmitChallengeResponse 59 60 def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 61 """Fulfill direct authorization requests that arrive via the SAML HTTP-POST binding. 62 Requests to the flow executor keep the regular challenge-response handling.""" 63 if self.executor.direct_execution: 64 return self.get(request, *args, **kwargs) 65 return super().post(request, *args, **kwargs) 66 67 def direct_error(self, message: str) -> HttpResponse: 68 """Render errors that bypass the flow interface as HTML.""" 69 return bad_request_message(self.request, message) 70 71 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 72 application: Application = self.executor.plan.context[PLAN_CONTEXT_APPLICATION] 73 provider: SAMLProvider = get_object_or_404(SAMLProvider, pk=application.provider_id) 74 if PLAN_CONTEXT_SAML_AUTH_N_REQUEST not in self.executor.plan.context: 75 self.logger.warning("No AuthNRequest in context") 76 if self.executor.direct_execution: 77 return self.direct_error(_("The SAML request payload is missing.")) 78 return self.executor.stage_invalid() 79 80 auth_n_request: AuthNRequest = self.executor.plan.context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] 81 try: 82 processor = AssertionProcessor(provider, request, auth_n_request) 83 response = processor.build_response() 84 85 # Create SAMLSession to track this login 86 auth_session = AuthenticatedSession.from_request(request, request.user) 87 if auth_session: 88 # Since samlsessions should only exist uniquely for an active session and a provider 89 # any existing combination is likely an old, dead session 90 SAMLSession.objects.filter( 91 session_index=processor.session_index, provider=provider 92 ).delete() 93 94 SAMLSession.objects.update_or_create( 95 session_index=processor.session_index, 96 provider=provider, 97 defaults={ 98 "user": request.user, 99 "session": auth_session, 100 "name_id": processor.name_id, 101 "name_id_format": processor.name_id_format, 102 "issuer": processor.issuer, 103 "expires": processor.session_not_on_or_after_datetime, 104 "expiring": True, 105 }, 106 ) 107 except SAMLException as exc: 108 Event.new( 109 EventAction.CONFIGURATION_ERROR, 110 message=f"Failed to process SAML assertion: {str(exc)}", 111 provider=provider, 112 ).from_http(self.request) 113 if self.executor.direct_execution: 114 return self.direct_error(_("Failed to process SAML assertion.")) 115 return self.executor.stage_invalid() 116 117 # Log Application Authorization 118 Event.new( 119 EventAction.AUTHORIZE_APPLICATION, 120 authorized_application=application, 121 flow=self.executor.plan.flow_pk, 122 ).from_http(self.request) 123 124 if provider.sp_binding == SAMLBindings.POST: 125 form_attrs = delete_none_values( 126 { 127 REQUEST_KEY_SAML_RESPONSE: nice64(response), 128 REQUEST_KEY_RELAY_STATE: auth_n_request.relay_state, 129 } 130 ) 131 if self.executor.direct_execution: 132 direct_response = TemplateResponse( 133 request, 134 "if/saml_form_post.html", 135 {"redirect_uri": provider.acs_url, "attrs": form_attrs}, 136 ) 137 add_never_cache_headers(direct_response) 138 direct_response["Pragma"] = "no-cache" 139 return direct_response 140 return super().get( 141 self.request, 142 **{ 143 "component": "ak-stage-autosubmit", 144 "title": self.executor.plan.context.get( 145 PLAN_CONTEXT_TITLE, 146 _("Redirecting to {app}...").format(app=application.name), 147 ), 148 "url": provider.acs_url, 149 "attrs": form_attrs, 150 }, 151 ) 152 if provider.sp_binding == SAMLBindings.REDIRECT: 153 Event.log_deprecation( 154 DEPRECATION_SP_BINDING_REDIRECT, 155 ( 156 "Redirect binding for Service Provider binding is deprecated " 157 "and will be removed in a future version. Use Post binding instead." 158 ), 159 cause=provider.name, 160 ) 161 url_args = { 162 REQUEST_KEY_SAML_RESPONSE: deflate_and_base64_encode(response), 163 } 164 if auth_n_request.relay_state: 165 url_args[REQUEST_KEY_RELAY_STATE] = auth_n_request.relay_state 166 querystring = urlencode(url_args) 167 if ContinuousLogin.get() and not self.executor.direct_execution: 168 return HttpChallengeResponse( 169 RedirectChallenge( 170 instance={ 171 "to": f"{provider.acs_url}?{querystring}", 172 "final_redirect": True, 173 } 174 ) 175 ) 176 return redirect(f"{provider.acs_url}?{querystring}") 177 return bad_request_message(request, _("Invalid sp_binding specified")) 178 179 def get_challenge(self, *args, **kwargs) -> Challenge: 180 return AutosubmitChallenge(data=kwargs) 181 182 def challenge_valid(self, response: ChallengeResponse) -> HttpResponse: 183 # We'll never get here since the challenge redirects to the SP 184 return HttpResponseBadRequest()
LOGGER =
<BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
URL_VALIDATOR =
<django.core.validators.URLValidator object>
REQUEST_KEY_SAML_REQUEST =
'SAMLRequest'
REQUEST_KEY_SAML_SIGNATURE =
'Signature'
REQUEST_KEY_SAML_SIG_ALG =
'SigAlg'
REQUEST_KEY_SAML_RESPONSE =
'SAMLResponse'
REQUEST_KEY_RELAY_STATE =
'RelayState'
DEPRECATION_SP_BINDING_REDIRECT =
'authentik.providers.saml.sp_binding_redirect'
PLAN_CONTEXT_SAML_AUTH_N_REQUEST =
'authentik/providers/saml/authn_request'
PLAN_CONTEXT_SAML_LOGOUT_REQUEST =
'authentik/providers/saml/logout_request'
PLAN_CONTEXT_SAML_LOGOUT_NATIVE_SESSIONS =
'goauthentik.io/providers/saml/native_sessions'
PLAN_CONTEXT_SAML_LOGOUT_IFRAME_SESSIONS =
'goauthentik.io/providers/saml/iframe_sessions'
PLAN_CONTEXT_SAML_RELAY_STATE =
'goauthentik.io/providers/saml/relay_state'
54class SAMLFlowFinalView(ChallengeStageView): 55 """View used by FlowExecutor after all stages have passed. Logs the authorization, 56 and redirects to the SP (if REDIRECT is configured) or shows an auto-submit element 57 (if POST is configured).""" 58 59 response_class = AutoSubmitChallengeResponse 60 61 def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 62 """Fulfill direct authorization requests that arrive via the SAML HTTP-POST binding. 63 Requests to the flow executor keep the regular challenge-response handling.""" 64 if self.executor.direct_execution: 65 return self.get(request, *args, **kwargs) 66 return super().post(request, *args, **kwargs) 67 68 def direct_error(self, message: str) -> HttpResponse: 69 """Render errors that bypass the flow interface as HTML.""" 70 return bad_request_message(self.request, message) 71 72 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 73 application: Application = self.executor.plan.context[PLAN_CONTEXT_APPLICATION] 74 provider: SAMLProvider = get_object_or_404(SAMLProvider, pk=application.provider_id) 75 if PLAN_CONTEXT_SAML_AUTH_N_REQUEST not in self.executor.plan.context: 76 self.logger.warning("No AuthNRequest in context") 77 if self.executor.direct_execution: 78 return self.direct_error(_("The SAML request payload is missing.")) 79 return self.executor.stage_invalid() 80 81 auth_n_request: AuthNRequest = self.executor.plan.context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] 82 try: 83 processor = AssertionProcessor(provider, request, auth_n_request) 84 response = processor.build_response() 85 86 # Create SAMLSession to track this login 87 auth_session = AuthenticatedSession.from_request(request, request.user) 88 if auth_session: 89 # Since samlsessions should only exist uniquely for an active session and a provider 90 # any existing combination is likely an old, dead session 91 SAMLSession.objects.filter( 92 session_index=processor.session_index, provider=provider 93 ).delete() 94 95 SAMLSession.objects.update_or_create( 96 session_index=processor.session_index, 97 provider=provider, 98 defaults={ 99 "user": request.user, 100 "session": auth_session, 101 "name_id": processor.name_id, 102 "name_id_format": processor.name_id_format, 103 "issuer": processor.issuer, 104 "expires": processor.session_not_on_or_after_datetime, 105 "expiring": True, 106 }, 107 ) 108 except SAMLException as exc: 109 Event.new( 110 EventAction.CONFIGURATION_ERROR, 111 message=f"Failed to process SAML assertion: {str(exc)}", 112 provider=provider, 113 ).from_http(self.request) 114 if self.executor.direct_execution: 115 return self.direct_error(_("Failed to process SAML assertion.")) 116 return self.executor.stage_invalid() 117 118 # Log Application Authorization 119 Event.new( 120 EventAction.AUTHORIZE_APPLICATION, 121 authorized_application=application, 122 flow=self.executor.plan.flow_pk, 123 ).from_http(self.request) 124 125 if provider.sp_binding == SAMLBindings.POST: 126 form_attrs = delete_none_values( 127 { 128 REQUEST_KEY_SAML_RESPONSE: nice64(response), 129 REQUEST_KEY_RELAY_STATE: auth_n_request.relay_state, 130 } 131 ) 132 if self.executor.direct_execution: 133 direct_response = TemplateResponse( 134 request, 135 "if/saml_form_post.html", 136 {"redirect_uri": provider.acs_url, "attrs": form_attrs}, 137 ) 138 add_never_cache_headers(direct_response) 139 direct_response["Pragma"] = "no-cache" 140 return direct_response 141 return super().get( 142 self.request, 143 **{ 144 "component": "ak-stage-autosubmit", 145 "title": self.executor.plan.context.get( 146 PLAN_CONTEXT_TITLE, 147 _("Redirecting to {app}...").format(app=application.name), 148 ), 149 "url": provider.acs_url, 150 "attrs": form_attrs, 151 }, 152 ) 153 if provider.sp_binding == SAMLBindings.REDIRECT: 154 Event.log_deprecation( 155 DEPRECATION_SP_BINDING_REDIRECT, 156 ( 157 "Redirect binding for Service Provider binding is deprecated " 158 "and will be removed in a future version. Use Post binding instead." 159 ), 160 cause=provider.name, 161 ) 162 url_args = { 163 REQUEST_KEY_SAML_RESPONSE: deflate_and_base64_encode(response), 164 } 165 if auth_n_request.relay_state: 166 url_args[REQUEST_KEY_RELAY_STATE] = auth_n_request.relay_state 167 querystring = urlencode(url_args) 168 if ContinuousLogin.get() and not self.executor.direct_execution: 169 return HttpChallengeResponse( 170 RedirectChallenge( 171 instance={ 172 "to": f"{provider.acs_url}?{querystring}", 173 "final_redirect": True, 174 } 175 ) 176 ) 177 return redirect(f"{provider.acs_url}?{querystring}") 178 return bad_request_message(request, _("Invalid sp_binding specified")) 179 180 def get_challenge(self, *args, **kwargs) -> Challenge: 181 return AutosubmitChallenge(data=kwargs) 182 183 def challenge_valid(self, response: ChallengeResponse) -> HttpResponse: 184 # We'll never get here since the challenge redirects to the SP 185 return HttpResponseBadRequest()
View used by FlowExecutor after all stages have passed. Logs the authorization, and redirects to the SP (if REDIRECT is configured) or shows an auto-submit element (if POST is configured).
response_class =
<class 'authentik.flows.challenge.AutoSubmitChallengeResponse'>
def
post( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
61 def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 62 """Fulfill direct authorization requests that arrive via the SAML HTTP-POST binding. 63 Requests to the flow executor keep the regular challenge-response handling.""" 64 if self.executor.direct_execution: 65 return self.get(request, *args, **kwargs) 66 return super().post(request, *args, **kwargs)
Fulfill direct authorization requests that arrive via the SAML HTTP-POST binding. Requests to the flow executor keep the regular challenge-response handling.
def
direct_error(self, message: str) -> django.http.response.HttpResponse:
68 def direct_error(self, message: str) -> HttpResponse: 69 """Render errors that bypass the flow interface as HTML.""" 70 return bad_request_message(self.request, message)
Render errors that bypass the flow interface as HTML.
def
get( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
72 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 73 application: Application = self.executor.plan.context[PLAN_CONTEXT_APPLICATION] 74 provider: SAMLProvider = get_object_or_404(SAMLProvider, pk=application.provider_id) 75 if PLAN_CONTEXT_SAML_AUTH_N_REQUEST not in self.executor.plan.context: 76 self.logger.warning("No AuthNRequest in context") 77 if self.executor.direct_execution: 78 return self.direct_error(_("The SAML request payload is missing.")) 79 return self.executor.stage_invalid() 80 81 auth_n_request: AuthNRequest = self.executor.plan.context[PLAN_CONTEXT_SAML_AUTH_N_REQUEST] 82 try: 83 processor = AssertionProcessor(provider, request, auth_n_request) 84 response = processor.build_response() 85 86 # Create SAMLSession to track this login 87 auth_session = AuthenticatedSession.from_request(request, request.user) 88 if auth_session: 89 # Since samlsessions should only exist uniquely for an active session and a provider 90 # any existing combination is likely an old, dead session 91 SAMLSession.objects.filter( 92 session_index=processor.session_index, provider=provider 93 ).delete() 94 95 SAMLSession.objects.update_or_create( 96 session_index=processor.session_index, 97 provider=provider, 98 defaults={ 99 "user": request.user, 100 "session": auth_session, 101 "name_id": processor.name_id, 102 "name_id_format": processor.name_id_format, 103 "issuer": processor.issuer, 104 "expires": processor.session_not_on_or_after_datetime, 105 "expiring": True, 106 }, 107 ) 108 except SAMLException as exc: 109 Event.new( 110 EventAction.CONFIGURATION_ERROR, 111 message=f"Failed to process SAML assertion: {str(exc)}", 112 provider=provider, 113 ).from_http(self.request) 114 if self.executor.direct_execution: 115 return self.direct_error(_("Failed to process SAML assertion.")) 116 return self.executor.stage_invalid() 117 118 # Log Application Authorization 119 Event.new( 120 EventAction.AUTHORIZE_APPLICATION, 121 authorized_application=application, 122 flow=self.executor.plan.flow_pk, 123 ).from_http(self.request) 124 125 if provider.sp_binding == SAMLBindings.POST: 126 form_attrs = delete_none_values( 127 { 128 REQUEST_KEY_SAML_RESPONSE: nice64(response), 129 REQUEST_KEY_RELAY_STATE: auth_n_request.relay_state, 130 } 131 ) 132 if self.executor.direct_execution: 133 direct_response = TemplateResponse( 134 request, 135 "if/saml_form_post.html", 136 {"redirect_uri": provider.acs_url, "attrs": form_attrs}, 137 ) 138 add_never_cache_headers(direct_response) 139 direct_response["Pragma"] = "no-cache" 140 return direct_response 141 return super().get( 142 self.request, 143 **{ 144 "component": "ak-stage-autosubmit", 145 "title": self.executor.plan.context.get( 146 PLAN_CONTEXT_TITLE, 147 _("Redirecting to {app}...").format(app=application.name), 148 ), 149 "url": provider.acs_url, 150 "attrs": form_attrs, 151 }, 152 ) 153 if provider.sp_binding == SAMLBindings.REDIRECT: 154 Event.log_deprecation( 155 DEPRECATION_SP_BINDING_REDIRECT, 156 ( 157 "Redirect binding for Service Provider binding is deprecated " 158 "and will be removed in a future version. Use Post binding instead." 159 ), 160 cause=provider.name, 161 ) 162 url_args = { 163 REQUEST_KEY_SAML_RESPONSE: deflate_and_base64_encode(response), 164 } 165 if auth_n_request.relay_state: 166 url_args[REQUEST_KEY_RELAY_STATE] = auth_n_request.relay_state 167 querystring = urlencode(url_args) 168 if ContinuousLogin.get() and not self.executor.direct_execution: 169 return HttpChallengeResponse( 170 RedirectChallenge( 171 instance={ 172 "to": f"{provider.acs_url}?{querystring}", 173 "final_redirect": True, 174 } 175 ) 176 ) 177 return redirect(f"{provider.acs_url}?{querystring}") 178 return bad_request_message(request, _("Invalid sp_binding specified"))
Return a challenge for the frontend to solve
180 def get_challenge(self, *args, **kwargs) -> Challenge: 181 return AutosubmitChallenge(data=kwargs)
Return the challenge that the client should solve
def
challenge_valid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
183 def challenge_valid(self, response: ChallengeResponse) -> HttpResponse: 184 # We'll never get here since the challenge redirects to the SP 185 return HttpResponseBadRequest()
Callback when the challenge has the correct format