authentik.flows.stage

authentik stage Base view

  1"""authentik stage Base view"""
  2
  3from typing import TYPE_CHECKING
  4from urllib.parse import urlencode
  5
  6from django.conf import settings
  7from django.contrib.auth.models import AnonymousUser
  8from django.contrib.messages import get_messages
  9from django.http import HttpRequest
 10from django.http.request import QueryDict
 11from django.http.response import HttpResponse
 12from django.urls import reverse
 13from django.views.generic.base import View
 14from prometheus_client import Histogram
 15from rest_framework.request import Request
 16from structlog.stdlib import BoundLogger, get_logger
 17
 18from authentik.common.oauth.constants import PLAN_CONTEXT_POST_LOGOUT_REDIRECT_URI
 19from authentik.core.models import Application, User, UserTypes
 20from authentik.flows.challenge import (
 21    AccessDeniedChallenge,
 22    Challenge,
 23    ChallengeResponse,
 24    ContextualFlowInfo,
 25    FlowMessageSerializer,
 26    HttpChallengeResponse,
 27    RedirectChallenge,
 28    SessionEndChallenge,
 29    WithUserInfoChallenge,
 30)
 31from authentik.flows.exceptions import StageInvalidException
 32from authentik.flows.models import Flow, InvalidResponseAction
 33from authentik.flows.planner import (
 34    PLAN_CONTEXT_APPLICATION,
 35    PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD,
 36    PLAN_CONTEXT_PENDING_USER,
 37    FlowPlan,
 38)
 39from authentik.lib.avatars import DEFAULT_AVATAR, get_avatar
 40from authentik.lib.tracing import active_tracer
 41from authentik.lib.utils.reflection import class_to_path
 42
 43if TYPE_CHECKING:
 44    from authentik.flows.views.executor import FlowExecutorView
 45
 46PLAN_CONTEXT_PENDING_USER_IDENTIFIER = "pending_user_identifier"
 47HIST_FLOWS_STAGE_TIME = Histogram(
 48    "authentik_flows_stage_time",
 49    "Duration taken by different parts of stages",
 50    ["stage_type", "method"],
 51)
 52LOGGER = get_logger()
 53
 54
 55def _get_pending_user(plan: FlowPlan | None, request: HttpRequest, for_display=False) -> User:
 56    """Either show the matched User object or show what the user entered,
 57    based on what the earlier stage (mostly IdentificationStage) set.
 58    _USER_IDENTIFIER overrides the first User, as PENDING_USER is used for
 59    other things besides the form display.
 60
 61    If no user is pending, returns request.user"""
 62    if not plan:
 63        return request.user
 64    if PLAN_CONTEXT_PENDING_USER_IDENTIFIER in plan.context and for_display:
 65        return User(
 66            username=plan.context.get(PLAN_CONTEXT_PENDING_USER_IDENTIFIER),
 67            email="",
 68        )
 69    if PLAN_CONTEXT_PENDING_USER in plan.context:
 70        return plan.context[PLAN_CONTEXT_PENDING_USER]
 71    return request.user
 72
 73
 74def format_flow_title(plan: FlowPlan | None, flow: Flow, request: HttpRequest) -> str:
 75    """Allow usage of placeholder in flow title."""
 76    data = {
 77        "app": "",
 78        "user": "",
 79    }
 80    if plan:
 81        data["app"] = plan.context.get(PLAN_CONTEXT_APPLICATION, "")
 82        user = _get_pending_user(plan, request, for_display=True)
 83        # Before the user is identified this is the AnonymousUser, which has no name to show
 84        if not user.is_anonymous:
 85            data["user"] = user
 86    try:
 87        return flow.title % data
 88
 89    except Exception as exc:  # noqa
 90        LOGGER.warning("failed to template title", exc=exc)
 91        return flow.title
 92
 93
 94class StageView(View):
 95    """Abstract Stage"""
 96
 97    executor: FlowExecutorView
 98
 99    request: HttpRequest = None
100
101    logger: BoundLogger
102
103    def __init__(self, executor: FlowExecutorView, **kwargs):
104        self.executor = executor
105        current_stage = getattr(self.executor, "current_stage", None)
106        self.logger = get_logger().bind(
107            stage=getattr(current_stage, "name", None),
108            stage_view=class_to_path(type(self)),
109        )
110        super().__init__(**kwargs)
111
112    def get_pending_user(self, for_display=False) -> User:
113        return _get_pending_user(self.executor.plan, self.request, for_display=for_display)
114
115    def cleanup(self):
116        """Cleanup session"""
117
118
119class ChallengeStageView(StageView):
120    """Stage view which response with a challenge"""
121
122    response_class = ChallengeResponse
123
124    def get_response_instance(self, data: QueryDict) -> ChallengeResponse:
125        """Return the response class type"""
126        return self.response_class(None, data=data, stage=self)
127
128    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
129        """Return a challenge for the frontend to solve"""
130        try:
131            challenge = self._get_challenge(*args, **kwargs)
132        except StageInvalidException as exc:
133            self.logger.debug("Got StageInvalidException", exc=exc)
134            return self.executor.stage_invalid()
135        if not challenge.is_valid():
136            self.logger.error(
137                "f(ch): Invalid challenge",
138                errors=challenge.errors,
139                challenge=challenge.data,
140            )
141        return HttpChallengeResponse(challenge)
142
143    def post(self, request: Request, *args, **kwargs) -> HttpResponse:
144        """Handle challenge response"""
145        valid = False
146        try:
147            challenge: ChallengeResponse = self.get_response_instance(data=request.data)
148            valid = challenge.is_valid()
149        except StageInvalidException as exc:
150            self.logger.debug("Got StageInvalidException", exc=exc)
151            return self.executor.stage_invalid()
152        if not valid:
153            if self.executor.current_binding.invalid_response_action in [
154                InvalidResponseAction.RESTART,
155                InvalidResponseAction.RESTART_WITH_CONTEXT,
156            ]:
157                keep_context = (
158                    self.executor.current_binding.invalid_response_action
159                    == InvalidResponseAction.RESTART_WITH_CONTEXT
160                )
161                self.logger.debug(
162                    "f(ch): Invalid response, restarting flow",
163                    keep_context=keep_context,
164                )
165                return self.executor.restart_flow(keep_context)
166            with (
167                active_tracer().start_span(
168                    op="authentik.flow.stage.challenge_invalid",
169                    name=self.__class__.__name__,
170                ),
171                HIST_FLOWS_STAGE_TIME.labels(
172                    stage_type=self.__class__.__name__, method="challenge_invalid"
173                ).time(),
174            ):
175                return self.challenge_invalid(challenge)
176        with (
177            active_tracer().start_span(
178                op="authentik.flow.stage.challenge_valid",
179                name=self.__class__.__name__,
180            ),
181            HIST_FLOWS_STAGE_TIME.labels(
182                stage_type=self.__class__.__name__, method="challenge_valid"
183            ).time(),
184        ):
185            return self.challenge_valid(challenge)
186
187    @property
188    def cancel_url(self) -> str:
189        from authentik.flows.views.executor import NEXT_ARG_NAME, SESSION_KEY_GET
190
191        next_param = self.request.session.get(SESSION_KEY_GET, {}).get(NEXT_ARG_NAME)
192        url = reverse("authentik_flows:cancel")
193        if next_param:
194            return f"{url}?{urlencode({NEXT_ARG_NAME: next_param})}"
195        return url
196
197    def _get_challenge(self, *args, **kwargs) -> Challenge:
198        with (
199            active_tracer().start_span(
200                op="authentik.flow.stage.get_challenge",
201                name=self.__class__.__name__,
202            ),
203            HIST_FLOWS_STAGE_TIME.labels(
204                stage_type=self.__class__.__name__, method="get_challenge"
205            ).time(),
206        ):
207            challenge = self.get_challenge(*args, **kwargs)
208        with active_tracer().start_span(
209            op="authentik.flow.stage._get_challenge",
210            name=self.__class__.__name__,
211        ):
212            if not hasattr(challenge, "initial_data"):
213                challenge.initial_data = {}
214            if "flow_info" not in challenge.initial_data:
215                messages = []
216                if self.request is not None and not isinstance(challenge, RedirectChallenge):
217                    messages = get_messages(self.request)
218                # Flow payloads can outlive the previous signed media JWT, so
219                # refreshes must mint fresh URLs instead of reusing cached ones.
220                flow_info_data = {
221                    "title": format_flow_title(
222                        self.executor.plan, self.executor.flow, self.request
223                    ),
224                    "background": self.executor.flow.background_url(use_cache=False),
225                    "background_themed_urls": self.executor.flow.background_themed_urls(
226                        use_cache=False,
227                    ),
228                    "cancel_url": self.cancel_url,
229                    "layout": self.executor.flow.layout,
230                    "messages": FlowMessageSerializer(messages, many=True).data,
231                }
232                plan_context = getattr(self.executor.plan, "context", {})
233                if PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD in plan_context:
234                    flow_info_data["continuous_login_hold"] = plan_context[
235                        PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD
236                    ]
237                flow_info = ContextualFlowInfo(data=flow_info_data)
238                flow_info.is_valid()
239                challenge.initial_data["flow_info"] = flow_info.data
240            if isinstance(challenge, WithUserInfoChallenge):
241                # If there's a pending user, update the `username` field
242                # this field is only used by password managers.
243                # If there's no user set, an error is raised later.
244                if user := self.get_pending_user(for_display=True):
245                    challenge.initial_data["pending_user"] = user.username
246                challenge.initial_data["pending_user_avatar"] = DEFAULT_AVATAR
247                if not isinstance(user, AnonymousUser):
248                    challenge.initial_data["pending_user_avatar"] = get_avatar(user, self.request)
249        return challenge
250
251    def get_challenge(self, *args, **kwargs) -> Challenge:
252        """Return the challenge that the client should solve"""
253        raise NotImplementedError
254
255    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
256        """Callback when the challenge has the correct format"""
257        raise NotImplementedError
258
259    def challenge_invalid(self, response: ChallengeResponse) -> HttpResponse:
260        """Callback when the challenge has the incorrect format"""
261        challenge_response = self._get_challenge()
262        full_errors = {}
263        for field, errors in response.errors.items():
264            for error in errors:
265                full_errors.setdefault(field, [])
266                field_error = {
267                    "string": str(error),
268                }
269                if hasattr(error, "code"):
270                    field_error["code"] = error.code
271                full_errors[field].append(field_error)
272        challenge_response.initial_data["response_errors"] = full_errors
273        if not challenge_response.is_valid():
274            if settings.TEST:
275                raise StageInvalidException(
276                    (
277                        f"Invalid challenge response: \n\t{challenge_response.errors}"
278                        f"\n\nValidated data:\n\t {challenge_response.data}"
279                        f"\n\nInitial data:\n\t {challenge_response.initial_data}"
280                    ),
281                )
282            self.logger.error(
283                "f(ch): invalid challenge response",
284                errors=challenge_response.errors,
285            )
286        return HttpChallengeResponse(challenge_response)
287
288
289class AccessDeniedStage(ChallengeStageView):
290    """Used internally by FlowExecutor's stage_invalid()"""
291
292    error_message: str | None
293
294    def __init__(self, executor: FlowExecutorView, error_message: str | None = None, **kwargs):
295        super().__init__(executor, **kwargs)
296        self.error_message = error_message
297
298    def get_challenge(self, *args, **kwargs) -> Challenge:
299        return AccessDeniedChallenge(
300            data={
301                "error_message": str(self.error_message or "Unknown error"),
302                "component": "ak-stage-access-denied",
303            }
304        )
305
306    # This can never be reached since this challenge is created on demand and only the
307    # .get() method is called
308    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:  # pragma: no cover
309        return self.executor.cancel()
310
311
312class RedirectStage(ChallengeStageView):
313    """Redirect to any URL"""
314
315    def get_challenge(self, *args, **kwargs) -> RedirectChallenge:
316        destination = getattr(
317            self.executor.current_stage, "destination", reverse("authentik_core:root-redirect")
318        )
319        return RedirectChallenge(
320            data={
321                "to": destination,
322            }
323        )
324
325    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
326        return HttpChallengeResponse(self.get_challenge())
327
328
329class SessionEndStage(ChallengeStageView):
330    """Stage inserted when a flow is used as invalidation flow. By default shows actions
331    that the user is likely to take after signing out of a provider."""
332
333    def get_challenge(self, *args, **kwargs) -> Challenge:
334        # Check for OIDC post_logout_redirect_uri in context
335        post_logout_redirect_uri = self.executor.plan.context.get(
336            PLAN_CONTEXT_POST_LOGOUT_REDIRECT_URI
337        )
338
339        if post_logout_redirect_uri:
340            self.logger.debug(
341                "SessionEndStage redirecting to post_logout_redirect_uri",
342                redirect_url=post_logout_redirect_uri,
343            )
344            return RedirectChallenge(
345                data={
346                    "to": post_logout_redirect_uri,
347                },
348            )
349
350        if not self.request.user.is_authenticated:
351            # User is logged out with no redirect URI - go to default
352            return RedirectChallenge(
353                data={
354                    "to": reverse("authentik_core:root-redirect"),
355                },
356            )
357        application: Application | None = self.executor.plan.context.get(PLAN_CONTEXT_APPLICATION)
358        data = {
359            "component": "ak-stage-session-end",
360            "brand_name": self.request.brand.branding_title,
361        }
362        if self.get_pending_user().type == UserTypes.INTERNAL:
363            data["overview_url"] = self.request.build_absolute_uri(
364                reverse("authentik_core:root-redirect")
365            )
366        if application:
367            data["application_name"] = application.name
368            if launch_url := application.get_launch_url(self.get_pending_user()):
369                data["application_launch_url"] = launch_url
370        if self.request.brand.flow_invalidation:
371            data["invalidation_flow_url"] = reverse(
372                "authentik_core:if-flow",
373                kwargs={
374                    "flow_slug": self.request.brand.flow_invalidation.slug,
375                },
376            )
377
378        return SessionEndChallenge(data=data)
379
380    # This can never be reached since this challenge is created on demand and only the
381    # .get() method is called
382    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:  # pragma: no cover
383        return self.executor.cancel()
PLAN_CONTEXT_PENDING_USER_IDENTIFIER = 'pending_user_identifier'
HIST_FLOWS_STAGE_TIME = prometheus_client.metrics.Histogram(authentik_flows_stage_time)
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
def format_flow_title( plan: authentik.flows.planner.FlowPlan | None, flow: authentik.flows.models.Flow, request: django.http.request.HttpRequest) -> str:
75def format_flow_title(plan: FlowPlan | None, flow: Flow, request: HttpRequest) -> str:
76    """Allow usage of placeholder in flow title."""
77    data = {
78        "app": "",
79        "user": "",
80    }
81    if plan:
82        data["app"] = plan.context.get(PLAN_CONTEXT_APPLICATION, "")
83        user = _get_pending_user(plan, request, for_display=True)
84        # Before the user is identified this is the AnonymousUser, which has no name to show
85        if not user.is_anonymous:
86            data["user"] = user
87    try:
88        return flow.title % data
89
90    except Exception as exc:  # noqa
91        LOGGER.warning("failed to template title", exc=exc)
92        return flow.title

Allow usage of placeholder in flow title.

class StageView(django.views.generic.base.View):
 95class StageView(View):
 96    """Abstract Stage"""
 97
 98    executor: FlowExecutorView
 99
100    request: HttpRequest = None
101
102    logger: BoundLogger
103
104    def __init__(self, executor: FlowExecutorView, **kwargs):
105        self.executor = executor
106        current_stage = getattr(self.executor, "current_stage", None)
107        self.logger = get_logger().bind(
108            stage=getattr(current_stage, "name", None),
109            stage_view=class_to_path(type(self)),
110        )
111        super().__init__(**kwargs)
112
113    def get_pending_user(self, for_display=False) -> User:
114        return _get_pending_user(self.executor.plan, self.request, for_display=for_display)
115
116    def cleanup(self):
117        """Cleanup session"""

Abstract Stage

StageView(executor: authentik.flows.views.executor.FlowExecutorView, **kwargs)
104    def __init__(self, executor: FlowExecutorView, **kwargs):
105        self.executor = executor
106        current_stage = getattr(self.executor, "current_stage", None)
107        self.logger = get_logger().bind(
108            stage=getattr(current_stage, "name", None),
109            stage_view=class_to_path(type(self)),
110        )
111        super().__init__(**kwargs)

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

request: django.http.request.HttpRequest = None
logger: structlog.stdlib.BoundLogger
def get_pending_user(self, for_display=False) -> authentik.core.models.User:
113    def get_pending_user(self, for_display=False) -> User:
114        return _get_pending_user(self.executor.plan, self.request, for_display=for_display)
def cleanup(self):
116    def cleanup(self):
117        """Cleanup session"""

Cleanup session

class ChallengeStageView(StageView):
120class ChallengeStageView(StageView):
121    """Stage view which response with a challenge"""
122
123    response_class = ChallengeResponse
124
125    def get_response_instance(self, data: QueryDict) -> ChallengeResponse:
126        """Return the response class type"""
127        return self.response_class(None, data=data, stage=self)
128
129    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
130        """Return a challenge for the frontend to solve"""
131        try:
132            challenge = self._get_challenge(*args, **kwargs)
133        except StageInvalidException as exc:
134            self.logger.debug("Got StageInvalidException", exc=exc)
135            return self.executor.stage_invalid()
136        if not challenge.is_valid():
137            self.logger.error(
138                "f(ch): Invalid challenge",
139                errors=challenge.errors,
140                challenge=challenge.data,
141            )
142        return HttpChallengeResponse(challenge)
143
144    def post(self, request: Request, *args, **kwargs) -> HttpResponse:
145        """Handle challenge response"""
146        valid = False
147        try:
148            challenge: ChallengeResponse = self.get_response_instance(data=request.data)
149            valid = challenge.is_valid()
150        except StageInvalidException as exc:
151            self.logger.debug("Got StageInvalidException", exc=exc)
152            return self.executor.stage_invalid()
153        if not valid:
154            if self.executor.current_binding.invalid_response_action in [
155                InvalidResponseAction.RESTART,
156                InvalidResponseAction.RESTART_WITH_CONTEXT,
157            ]:
158                keep_context = (
159                    self.executor.current_binding.invalid_response_action
160                    == InvalidResponseAction.RESTART_WITH_CONTEXT
161                )
162                self.logger.debug(
163                    "f(ch): Invalid response, restarting flow",
164                    keep_context=keep_context,
165                )
166                return self.executor.restart_flow(keep_context)
167            with (
168                active_tracer().start_span(
169                    op="authentik.flow.stage.challenge_invalid",
170                    name=self.__class__.__name__,
171                ),
172                HIST_FLOWS_STAGE_TIME.labels(
173                    stage_type=self.__class__.__name__, method="challenge_invalid"
174                ).time(),
175            ):
176                return self.challenge_invalid(challenge)
177        with (
178            active_tracer().start_span(
179                op="authentik.flow.stage.challenge_valid",
180                name=self.__class__.__name__,
181            ),
182            HIST_FLOWS_STAGE_TIME.labels(
183                stage_type=self.__class__.__name__, method="challenge_valid"
184            ).time(),
185        ):
186            return self.challenge_valid(challenge)
187
188    @property
189    def cancel_url(self) -> str:
190        from authentik.flows.views.executor import NEXT_ARG_NAME, SESSION_KEY_GET
191
192        next_param = self.request.session.get(SESSION_KEY_GET, {}).get(NEXT_ARG_NAME)
193        url = reverse("authentik_flows:cancel")
194        if next_param:
195            return f"{url}?{urlencode({NEXT_ARG_NAME: next_param})}"
196        return url
197
198    def _get_challenge(self, *args, **kwargs) -> Challenge:
199        with (
200            active_tracer().start_span(
201                op="authentik.flow.stage.get_challenge",
202                name=self.__class__.__name__,
203            ),
204            HIST_FLOWS_STAGE_TIME.labels(
205                stage_type=self.__class__.__name__, method="get_challenge"
206            ).time(),
207        ):
208            challenge = self.get_challenge(*args, **kwargs)
209        with active_tracer().start_span(
210            op="authentik.flow.stage._get_challenge",
211            name=self.__class__.__name__,
212        ):
213            if not hasattr(challenge, "initial_data"):
214                challenge.initial_data = {}
215            if "flow_info" not in challenge.initial_data:
216                messages = []
217                if self.request is not None and not isinstance(challenge, RedirectChallenge):
218                    messages = get_messages(self.request)
219                # Flow payloads can outlive the previous signed media JWT, so
220                # refreshes must mint fresh URLs instead of reusing cached ones.
221                flow_info_data = {
222                    "title": format_flow_title(
223                        self.executor.plan, self.executor.flow, self.request
224                    ),
225                    "background": self.executor.flow.background_url(use_cache=False),
226                    "background_themed_urls": self.executor.flow.background_themed_urls(
227                        use_cache=False,
228                    ),
229                    "cancel_url": self.cancel_url,
230                    "layout": self.executor.flow.layout,
231                    "messages": FlowMessageSerializer(messages, many=True).data,
232                }
233                plan_context = getattr(self.executor.plan, "context", {})
234                if PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD in plan_context:
235                    flow_info_data["continuous_login_hold"] = plan_context[
236                        PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD
237                    ]
238                flow_info = ContextualFlowInfo(data=flow_info_data)
239                flow_info.is_valid()
240                challenge.initial_data["flow_info"] = flow_info.data
241            if isinstance(challenge, WithUserInfoChallenge):
242                # If there's a pending user, update the `username` field
243                # this field is only used by password managers.
244                # If there's no user set, an error is raised later.
245                if user := self.get_pending_user(for_display=True):
246                    challenge.initial_data["pending_user"] = user.username
247                challenge.initial_data["pending_user_avatar"] = DEFAULT_AVATAR
248                if not isinstance(user, AnonymousUser):
249                    challenge.initial_data["pending_user_avatar"] = get_avatar(user, self.request)
250        return challenge
251
252    def get_challenge(self, *args, **kwargs) -> Challenge:
253        """Return the challenge that the client should solve"""
254        raise NotImplementedError
255
256    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
257        """Callback when the challenge has the correct format"""
258        raise NotImplementedError
259
260    def challenge_invalid(self, response: ChallengeResponse) -> HttpResponse:
261        """Callback when the challenge has the incorrect format"""
262        challenge_response = self._get_challenge()
263        full_errors = {}
264        for field, errors in response.errors.items():
265            for error in errors:
266                full_errors.setdefault(field, [])
267                field_error = {
268                    "string": str(error),
269                }
270                if hasattr(error, "code"):
271                    field_error["code"] = error.code
272                full_errors[field].append(field_error)
273        challenge_response.initial_data["response_errors"] = full_errors
274        if not challenge_response.is_valid():
275            if settings.TEST:
276                raise StageInvalidException(
277                    (
278                        f"Invalid challenge response: \n\t{challenge_response.errors}"
279                        f"\n\nValidated data:\n\t {challenge_response.data}"
280                        f"\n\nInitial data:\n\t {challenge_response.initial_data}"
281                    ),
282                )
283            self.logger.error(
284                "f(ch): invalid challenge response",
285                errors=challenge_response.errors,
286            )
287        return HttpChallengeResponse(challenge_response)

Stage view which response with a challenge

response_class = <class 'authentik.flows.challenge.ChallengeResponse'>
def get_response_instance( self, data: django.http.request.QueryDict) -> authentik.flows.challenge.ChallengeResponse:
125    def get_response_instance(self, data: QueryDict) -> ChallengeResponse:
126        """Return the response class type"""
127        return self.response_class(None, data=data, stage=self)

Return the response class type

def get( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
129    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
130        """Return a challenge for the frontend to solve"""
131        try:
132            challenge = self._get_challenge(*args, **kwargs)
133        except StageInvalidException as exc:
134            self.logger.debug("Got StageInvalidException", exc=exc)
135            return self.executor.stage_invalid()
136        if not challenge.is_valid():
137            self.logger.error(
138                "f(ch): Invalid challenge",
139                errors=challenge.errors,
140                challenge=challenge.data,
141            )
142        return HttpChallengeResponse(challenge)

Return a challenge for the frontend to solve

def post( self, request: rest_framework.request.Request, *args, **kwargs) -> django.http.response.HttpResponse:
144    def post(self, request: Request, *args, **kwargs) -> HttpResponse:
145        """Handle challenge response"""
146        valid = False
147        try:
148            challenge: ChallengeResponse = self.get_response_instance(data=request.data)
149            valid = challenge.is_valid()
150        except StageInvalidException as exc:
151            self.logger.debug("Got StageInvalidException", exc=exc)
152            return self.executor.stage_invalid()
153        if not valid:
154            if self.executor.current_binding.invalid_response_action in [
155                InvalidResponseAction.RESTART,
156                InvalidResponseAction.RESTART_WITH_CONTEXT,
157            ]:
158                keep_context = (
159                    self.executor.current_binding.invalid_response_action
160                    == InvalidResponseAction.RESTART_WITH_CONTEXT
161                )
162                self.logger.debug(
163                    "f(ch): Invalid response, restarting flow",
164                    keep_context=keep_context,
165                )
166                return self.executor.restart_flow(keep_context)
167            with (
168                active_tracer().start_span(
169                    op="authentik.flow.stage.challenge_invalid",
170                    name=self.__class__.__name__,
171                ),
172                HIST_FLOWS_STAGE_TIME.labels(
173                    stage_type=self.__class__.__name__, method="challenge_invalid"
174                ).time(),
175            ):
176                return self.challenge_invalid(challenge)
177        with (
178            active_tracer().start_span(
179                op="authentik.flow.stage.challenge_valid",
180                name=self.__class__.__name__,
181            ),
182            HIST_FLOWS_STAGE_TIME.labels(
183                stage_type=self.__class__.__name__, method="challenge_valid"
184            ).time(),
185        ):
186            return self.challenge_valid(challenge)

Handle challenge response

cancel_url: str
188    @property
189    def cancel_url(self) -> str:
190        from authentik.flows.views.executor import NEXT_ARG_NAME, SESSION_KEY_GET
191
192        next_param = self.request.session.get(SESSION_KEY_GET, {}).get(NEXT_ARG_NAME)
193        url = reverse("authentik_flows:cancel")
194        if next_param:
195            return f"{url}?{urlencode({NEXT_ARG_NAME: next_param})}"
196        return url
def get_challenge(self, *args, **kwargs) -> authentik.flows.challenge.Challenge:
252    def get_challenge(self, *args, **kwargs) -> Challenge:
253        """Return the challenge that the client should solve"""
254        raise NotImplementedError

Return the challenge that the client should solve

def challenge_valid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
256    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
257        """Callback when the challenge has the correct format"""
258        raise NotImplementedError

Callback when the challenge has the correct format

def challenge_invalid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
260    def challenge_invalid(self, response: ChallengeResponse) -> HttpResponse:
261        """Callback when the challenge has the incorrect format"""
262        challenge_response = self._get_challenge()
263        full_errors = {}
264        for field, errors in response.errors.items():
265            for error in errors:
266                full_errors.setdefault(field, [])
267                field_error = {
268                    "string": str(error),
269                }
270                if hasattr(error, "code"):
271                    field_error["code"] = error.code
272                full_errors[field].append(field_error)
273        challenge_response.initial_data["response_errors"] = full_errors
274        if not challenge_response.is_valid():
275            if settings.TEST:
276                raise StageInvalidException(
277                    (
278                        f"Invalid challenge response: \n\t{challenge_response.errors}"
279                        f"\n\nValidated data:\n\t {challenge_response.data}"
280                        f"\n\nInitial data:\n\t {challenge_response.initial_data}"
281                    ),
282                )
283            self.logger.error(
284                "f(ch): invalid challenge response",
285                errors=challenge_response.errors,
286            )
287        return HttpChallengeResponse(challenge_response)

Callback when the challenge has the incorrect format

class AccessDeniedStage(ChallengeStageView):
290class AccessDeniedStage(ChallengeStageView):
291    """Used internally by FlowExecutor's stage_invalid()"""
292
293    error_message: str | None
294
295    def __init__(self, executor: FlowExecutorView, error_message: str | None = None, **kwargs):
296        super().__init__(executor, **kwargs)
297        self.error_message = error_message
298
299    def get_challenge(self, *args, **kwargs) -> Challenge:
300        return AccessDeniedChallenge(
301            data={
302                "error_message": str(self.error_message or "Unknown error"),
303                "component": "ak-stage-access-denied",
304            }
305        )
306
307    # This can never be reached since this challenge is created on demand and only the
308    # .get() method is called
309    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:  # pragma: no cover
310        return self.executor.cancel()

Used internally by FlowExecutor's stage_invalid()

AccessDeniedStage( executor: authentik.flows.views.executor.FlowExecutorView, error_message: str | None = None, **kwargs)
295    def __init__(self, executor: FlowExecutorView, error_message: str | None = None, **kwargs):
296        super().__init__(executor, **kwargs)
297        self.error_message = error_message

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

error_message: str | None
def get_challenge(self, *args, **kwargs) -> authentik.flows.challenge.Challenge:
299    def get_challenge(self, *args, **kwargs) -> Challenge:
300        return AccessDeniedChallenge(
301            data={
302                "error_message": str(self.error_message or "Unknown error"),
303                "component": "ak-stage-access-denied",
304            }
305        )

Return the challenge that the client should solve

def challenge_valid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
309    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:  # pragma: no cover
310        return self.executor.cancel()

Callback when the challenge has the correct format

class RedirectStage(ChallengeStageView):
313class RedirectStage(ChallengeStageView):
314    """Redirect to any URL"""
315
316    def get_challenge(self, *args, **kwargs) -> RedirectChallenge:
317        destination = getattr(
318            self.executor.current_stage, "destination", reverse("authentik_core:root-redirect")
319        )
320        return RedirectChallenge(
321            data={
322                "to": destination,
323            }
324        )
325
326    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
327        return HttpChallengeResponse(self.get_challenge())

Redirect to any URL

def get_challenge(self, *args, **kwargs) -> authentik.flows.challenge.RedirectChallenge:
316    def get_challenge(self, *args, **kwargs) -> RedirectChallenge:
317        destination = getattr(
318            self.executor.current_stage, "destination", reverse("authentik_core:root-redirect")
319        )
320        return RedirectChallenge(
321            data={
322                "to": destination,
323            }
324        )

Return the challenge that the client should solve

def challenge_valid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
326    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
327        return HttpChallengeResponse(self.get_challenge())

Callback when the challenge has the correct format

class SessionEndStage(ChallengeStageView):
330class SessionEndStage(ChallengeStageView):
331    """Stage inserted when a flow is used as invalidation flow. By default shows actions
332    that the user is likely to take after signing out of a provider."""
333
334    def get_challenge(self, *args, **kwargs) -> Challenge:
335        # Check for OIDC post_logout_redirect_uri in context
336        post_logout_redirect_uri = self.executor.plan.context.get(
337            PLAN_CONTEXT_POST_LOGOUT_REDIRECT_URI
338        )
339
340        if post_logout_redirect_uri:
341            self.logger.debug(
342                "SessionEndStage redirecting to post_logout_redirect_uri",
343                redirect_url=post_logout_redirect_uri,
344            )
345            return RedirectChallenge(
346                data={
347                    "to": post_logout_redirect_uri,
348                },
349            )
350
351        if not self.request.user.is_authenticated:
352            # User is logged out with no redirect URI - go to default
353            return RedirectChallenge(
354                data={
355                    "to": reverse("authentik_core:root-redirect"),
356                },
357            )
358        application: Application | None = self.executor.plan.context.get(PLAN_CONTEXT_APPLICATION)
359        data = {
360            "component": "ak-stage-session-end",
361            "brand_name": self.request.brand.branding_title,
362        }
363        if self.get_pending_user().type == UserTypes.INTERNAL:
364            data["overview_url"] = self.request.build_absolute_uri(
365                reverse("authentik_core:root-redirect")
366            )
367        if application:
368            data["application_name"] = application.name
369            if launch_url := application.get_launch_url(self.get_pending_user()):
370                data["application_launch_url"] = launch_url
371        if self.request.brand.flow_invalidation:
372            data["invalidation_flow_url"] = reverse(
373                "authentik_core:if-flow",
374                kwargs={
375                    "flow_slug": self.request.brand.flow_invalidation.slug,
376                },
377            )
378
379        return SessionEndChallenge(data=data)
380
381    # This can never be reached since this challenge is created on demand and only the
382    # .get() method is called
383    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:  # pragma: no cover
384        return self.executor.cancel()

Stage inserted when a flow is used as invalidation flow. By default shows actions that the user is likely to take after signing out of a provider.

def get_challenge(self, *args, **kwargs) -> authentik.flows.challenge.Challenge:
334    def get_challenge(self, *args, **kwargs) -> Challenge:
335        # Check for OIDC post_logout_redirect_uri in context
336        post_logout_redirect_uri = self.executor.plan.context.get(
337            PLAN_CONTEXT_POST_LOGOUT_REDIRECT_URI
338        )
339
340        if post_logout_redirect_uri:
341            self.logger.debug(
342                "SessionEndStage redirecting to post_logout_redirect_uri",
343                redirect_url=post_logout_redirect_uri,
344            )
345            return RedirectChallenge(
346                data={
347                    "to": post_logout_redirect_uri,
348                },
349            )
350
351        if not self.request.user.is_authenticated:
352            # User is logged out with no redirect URI - go to default
353            return RedirectChallenge(
354                data={
355                    "to": reverse("authentik_core:root-redirect"),
356                },
357            )
358        application: Application | None = self.executor.plan.context.get(PLAN_CONTEXT_APPLICATION)
359        data = {
360            "component": "ak-stage-session-end",
361            "brand_name": self.request.brand.branding_title,
362        }
363        if self.get_pending_user().type == UserTypes.INTERNAL:
364            data["overview_url"] = self.request.build_absolute_uri(
365                reverse("authentik_core:root-redirect")
366            )
367        if application:
368            data["application_name"] = application.name
369            if launch_url := application.get_launch_url(self.get_pending_user()):
370                data["application_launch_url"] = launch_url
371        if self.request.brand.flow_invalidation:
372            data["invalidation_flow_url"] = reverse(
373                "authentik_core:if-flow",
374                kwargs={
375                    "flow_slug": self.request.brand.flow_invalidation.slug,
376                },
377            )
378
379        return SessionEndChallenge(data=data)

Return the challenge that the client should solve

def challenge_valid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
383    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:  # pragma: no cover
384        return self.executor.cancel()

Callback when the challenge has the correct format