authentik.stages.identification.stage

Identification stage logic

  1"""Identification stage logic"""
  2
  3from dataclasses import asdict
  4from functools import cache
  5from typing import Any
  6
  7from django.contrib.auth.hashers import make_password
  8from django.core.exceptions import PermissionDenied
  9from django.db.models import Q
 10from django.http import HttpRequest, HttpResponse
 11from django.utils.timezone import now
 12from django.utils.translation import gettext as _
 13from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field
 14from rest_framework.fields import BooleanField, CharField, ChoiceField, DictField, ListField
 15from rest_framework.serializers import ValidationError
 16
 17from authentik.core.api.utils import JSONDictField, PassiveSerializer, ThemedUrlsSerializer
 18from authentik.core.models import Application, Source, User
 19from authentik.endpoints.connectors.agent.stage import PLAN_CONTEXT_DEVICE_AUTH_TOKEN
 20from authentik.endpoints.models import Device
 21from authentik.events.middleware import audit_ignore
 22from authentik.events.utils import sanitize_item
 23from authentik.flows.challenge import (
 24    Challenge,
 25    ChallengeResponse,
 26    RedirectChallenge,
 27)
 28from authentik.flows.models import FlowDesignation
 29from authentik.flows.planner import (
 30    PLAN_CONTEXT_APPLICATION,
 31    PLAN_CONTEXT_DEVICE,
 32    PLAN_CONTEXT_PENDING_USER,
 33)
 34from authentik.flows.stage import PLAN_CONTEXT_PENDING_USER_IDENTIFIER, ChallengeStageView
 35from authentik.flows.views.executor import SESSION_KEY_GET
 36from authentik.lib.avatars import DEFAULT_AVATAR
 37from authentik.lib.tracing import active_tracer
 38from authentik.lib.utils.reflection import all_subclasses, class_to_path
 39from authentik.lib.utils.urls import reverse_with_qs
 40from authentik.root.middleware import ClientIPMiddleware
 41from authentik.stages.authenticator_validate.challenge import (
 42    get_webauthn_challenge_without_user,
 43    validate_challenge_webauthn,
 44)
 45from authentik.stages.authenticator_webauthn.models import WebAuthnDevice
 46from authentik.stages.authenticator_webauthn.stage import PLAN_CONTEXT_WEBAUTHN_CHALLENGE
 47from authentik.stages.captcha.stage import (
 48    PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY,
 49    PLAN_CONTEXT_CAPTCHA_SITE_KEY,
 50    CaptchaChallenge,
 51    verify_captcha_token,
 52)
 53from authentik.stages.identification.models import IdentificationStage
 54from authentik.stages.identification.signals import identification_failed
 55from authentik.stages.password.lockout import PasswordLockout, PasswordLockoutResult
 56from authentik.stages.password.stage import (
 57    PLAN_CONTEXT_METHOD,
 58    PLAN_CONTEXT_METHOD_ARGS,
 59    authenticate,
 60)
 61
 62
 63class LoginChallengeMixin:
 64    """Base login challenge for Identification stage"""
 65
 66
 67def get_login_serializers():
 68    mapping = {
 69        RedirectChallenge().fields["component"].default: RedirectChallenge,
 70    }
 71    for cls in all_subclasses(LoginChallengeMixin):
 72        mapping[cls().fields["component"].default] = cls
 73    return mapping
 74
 75
 76@cache
 77def login_capable_source_subclasses() -> list[type[Source]]:
 78    """Concrete Source subclasses that can render a UI login button.
 79
 80    ``Source.ui_login_button`` returns None, so a source only reaches the
 81    challenge below if its subclass overrides it. Abstract subclasses are skipped
 82    because they have no table to join against.
 83    """
 84    return [
 85        source_type
 86        for source_type in all_subclasses(Source)
 87        if not source_type._meta.abstract
 88        and source_type.ui_login_button is not Source.ui_login_button
 89    ]
 90
 91
 92@extend_schema_field(
 93    PolymorphicProxySerializer(
 94        component_name="LoginChallengeTypes",
 95        serializers=get_login_serializers,
 96        resource_type_field_name="component",
 97    )
 98)
 99class ChallengeDictWrapper(DictField):
100    """Wrapper around DictField that annotates itself as challenge proxy"""
101
102
103class LoginSourceSerializer(PassiveSerializer):
104    """Serializer for Login buttons of sources"""
105
106    name = CharField()
107    icon_url = CharField(required=False, allow_null=True)
108    icon_themed_urls = ThemedUrlsSerializer(required=False, allow_null=True)
109    promoted = BooleanField(default=False)
110
111    challenge = ChallengeDictWrapper()
112
113
114class IdentificationChallenge(Challenge):
115    """Identification challenges with all UI elements"""
116
117    user_fields = ListField(child=CharField(), allow_empty=True, allow_null=True)
118    pending_user_identifier = CharField(required=False, allow_null=True)
119
120    password_fields = BooleanField()
121    allow_show_password = BooleanField(default=False)
122    application_pre = CharField(required=False)
123    application_pre_launch = CharField(required=False)
124    flow_designation = ChoiceField(FlowDesignation.choices)
125    captcha_stage = CaptchaChallenge(required=False, allow_null=True)
126
127    enroll_url = CharField(required=False)
128    recovery_url = CharField(required=False)
129    passwordless_url = CharField(required=False)
130    primary_action = CharField()
131    sources = LoginSourceSerializer(many=True, required=False)
132    show_source_labels = BooleanField()
133    enable_remember_me = BooleanField(required=False, default=True)
134
135    passkey_challenge = JSONDictField(required=False, allow_null=True)
136
137    component = CharField(default="ak-stage-identification")
138
139
140class IdentificationChallengeResponse(ChallengeResponse):
141    """Identification challenge"""
142
143    uid_field = CharField(required=False, allow_blank=True, allow_null=True)
144    password = CharField(required=False, allow_blank=True, allow_null=True)
145    captcha_token = CharField(required=False, allow_blank=True, allow_null=True)
146    passkey = JSONDictField(required=False, allow_null=True)
147    component = CharField(default="ak-stage-identification")
148
149    pre_user: User | None = None
150    passkey_device: WebAuthnDevice | None = None
151    lockout: PasswordLockoutResult | None = None
152
153    def _validate_passkey_response(self, passkey: dict) -> WebAuthnDevice:
154        """Validate passkey/WebAuthn response for passwordless authentication"""
155        # Get the webauthn_stage from the current IdentificationStage
156        current_stage: IdentificationStage = IdentificationStage.objects.get(
157            pk=self.stage.executor.current_stage.pk
158        )
159        return validate_challenge_webauthn(
160            passkey, self.stage, self.stage.get_pending_user(), current_stage.webauthn_stage
161        )
162
163    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
164        """Validate that user exists, and optionally their password, captcha token, or passkey"""
165        current_stage: IdentificationStage = self.stage.executor.current_stage
166        client_ip = ClientIPMiddleware.get_client_ip(self.stage.request)
167
168        # Check if this is a passkey authentication
169        passkey = attrs.get("passkey")
170        if passkey:
171            device = self._validate_passkey_response(passkey)
172            self.passkey_device = device
173            self.pre_user = device.user
174            # Set backend so password stage policy knows user is already authenticated
175            self.pre_user.backend = class_to_path(IdentificationStageView)
176            return attrs
177
178        # Standard username/password flow
179        uid_field = attrs.get("uid_field")
180        if not uid_field:
181            raise ValidationError(_("No identification data provided."))
182
183        pre_user = self.stage.get_user(uid_field)
184        if not pre_user:
185            with active_tracer().start_span(
186                op="authentik.stages.identification.validate_invalid_wait",
187                name="Sleep random time on invalid user identifier",
188            ):
189                # hash a random password on invalid identifier, same as with a valid identifier
190                make_password(make_password(None))
191            # Log in a similar format to Event.new(), but we don't want to create an event here
192            # as this stage is mostly used by unauthenticated users with very high rate limits
193            self.stage.logger.info(
194                "invalid_login",
195                identifier=uid_field,
196                client_ip=client_ip,
197                action="invalid_identifier",
198                context={
199                    "stage": sanitize_item(self.stage),
200                },
201            )
202            identification_failed.send(sender=self, request=self.stage.request, uid_field=uid_field)
203            # We set the pending_user even on failure so it's part of the context, even
204            # when the input is invalid
205            # This is so its part of the current flow plan, and on flow restart can be kept, and
206            # policies can be applied.
207            self.stage.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = User(
208                username=uid_field,
209                email=uid_field,
210            )
211            self.pre_user = self.stage.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
212            if not current_stage.show_matched_user:
213                self.stage.executor.plan.context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = uid_field
214            # when `pretend` is enabled, continue regardless
215            if current_stage.pretend_user_exists and not current_stage.password_stage:
216                return attrs
217            raise ValidationError(_("Failed to authenticate."))
218        self.pre_user = pre_user
219
220        # Captcha check
221        if captcha_stage := current_stage.captcha_stage:
222            captcha_token = attrs.get("captcha_token", None)
223            if not captcha_token:
224                self.stage.logger.warning("Token not set for captcha attempt")
225            try:
226                verify_captcha_token(
227                    captcha_stage,
228                    captcha_token,
229                    client_ip,
230                    key=self.stage.executor.plan.context.get(PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY),
231                )
232            except ValidationError:
233                raise ValidationError(_("Failed to authenticate.")) from None
234
235        # Password check
236        if current_stage.password_stage:
237            self._validate_password(current_stage, attrs.get("password", None))
238        return attrs
239
240    def _validate_password(self, current_stage: IdentificationStage, password: str | None):
241        """Authenticate the pre-identified user's password against the embedded stage"""
242        if not password:
243            self.stage.logger.warning("Password not set for ident+auth attempt")
244        try:
245            with active_tracer().start_span(
246                op="authentik.stages.identification.authenticate",
247                name="User authenticate call (combo stage)",
248            ):
249                user = authenticate(
250                    self.stage.request,
251                    current_stage.password_stage.backends,
252                    current_stage,
253                    username=self.pre_user.username,
254                    password=password,
255                )
256            result = PasswordLockout(current_stage.password_stage, self.stage.request).apply(
257                self.pre_user, user, self.stage.executor.plan.context
258            )
259            self.lockout = result
260            if not result.user:
261                error = _("Failed to authenticate.")
262                if result.last_attempt:
263                    error = current_stage.password_stage.last_attempt_warning_message or error
264                raise ValidationError(error)
265            self.pre_user = result.user
266        except PermissionDenied as exc:
267            raise ValidationError(str(exc)) from exc
268
269
270class IdentificationStageView(ChallengeStageView):
271    """Form to identify the user"""
272
273    response_class = IdentificationChallengeResponse
274
275    def challenge_invalid(self, response: IdentificationChallengeResponse) -> HttpResponse:
276        """Stop the flow once its embedded password stage reaches its lockout."""
277        current_stage: IdentificationStage = self.executor.current_stage
278        if current_stage.password_stage and response.lockout and response.lockout.lockout_reached:
279            return self.executor.stage_invalid(
280                current_stage.password_stage.lockout_message or _("Failed to authenticate.")
281            )
282        return super().challenge_invalid(response)
283
284    def get_user(self, uid_value: str) -> User | None:
285        """Find user instance. Returns None if no user was found."""
286        current_stage: IdentificationStage = self.executor.current_stage
287        query = Q()
288        for search_field in current_stage.user_fields:
289            model_field = {
290                "email": "email",
291                "username": "username",
292                "upn": "attributes__upn",
293            }[search_field]
294            if current_stage.case_insensitive_matching:
295                model_field += "__iexact"
296            else:
297                model_field += "__exact"
298            query |= Q(**{model_field: uid_value})
299        if not query:
300            self.logger.debug("Empty user query", query=query)
301            return None
302        user = User.objects.filter(query).first()
303        if user:
304            self.logger.debug("Found user", user=user.username, query=query)
305            return user
306        return None
307
308    def get_primary_action(self) -> str:
309        """Get the primary action label for this stage"""
310        if self.executor.flow.designation == FlowDesignation.AUTHENTICATION:
311            return _("Log in")
312        return _("Continue")
313
314    def get_passkey_challenge(self) -> dict | None:
315        """Generate a WebAuthn challenge for passkey/conditional UI authentication"""
316        # Refresh from DB to get the latest configuration
317        current_stage: IdentificationStage = IdentificationStage.objects.get(
318            pk=self.executor.current_stage.pk
319        )
320        if not current_stage.webauthn_stage:
321            self.logger.debug("No webauthn_stage configured")
322            return None
323        challenge = get_webauthn_challenge_without_user(self, current_stage.webauthn_stage)
324        self.logger.debug("Generated passkey challenge", challenge=challenge)
325        return challenge
326
327    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
328        """Check for existing pending user identifier and skip stage if possible"""
329        current_stage: IdentificationStage = self.executor.current_stage
330        pending_user_identifier = self.executor.plan.context.get(
331            PLAN_CONTEXT_PENDING_USER_IDENTIFIER
332        )
333
334        if not pending_user_identifier:
335            return super().get(request, *args, **kwargs)
336
337        # Only skip if this is a "simple" identification stage with no extra features
338        can_skip = (
339            not current_stage.password_stage
340            and not current_stage.captcha_stage
341            and not current_stage.webauthn_stage
342            and not self.executor.current_binding.policies.exists()
343        )
344
345        if can_skip:
346            # Use the normal validation flow (handles timing protection, logging, signals)
347            response = IdentificationChallengeResponse(
348                data={"uid_field": pending_user_identifier},
349                stage=self,
350            )
351            if response.is_valid():
352                return self.challenge_valid(response)
353            # Validation failed (user doesn't exist and pretend_user_exists is off)
354            # Don't pre-fill invalid username, fall through to show the challenge
355            self.executor.plan.context.pop(PLAN_CONTEXT_PENDING_USER_IDENTIFIER, None)
356
357        # Can't skip - just pre-fill the username field
358        return super().get(request, *args, **kwargs)
359
360    def get_challenge(self) -> Challenge:
361        current_stage: IdentificationStage = self.executor.current_stage
362        challenge = IdentificationChallenge(
363            data={
364                "component": "ak-stage-identification",
365                "primary_action": self.get_primary_action(),
366                "user_fields": current_stage.user_fields,
367                "password_fields": bool(current_stage.password_stage),
368                "captcha_stage": (
369                    {
370                        "js_url": current_stage.captcha_stage.js_url,
371                        "site_key": self.executor.plan.context.get(
372                            PLAN_CONTEXT_CAPTCHA_SITE_KEY,
373                            current_stage.captcha_stage.public_key,
374                        ),
375                        "interactive": current_stage.captcha_stage.interactive,
376                        "pending_user": "",
377                        "pending_user_avatar": DEFAULT_AVATAR,
378                    }
379                    if current_stage.captcha_stage
380                    else None
381                ),
382                "allow_show_password": bool(current_stage.password_stage)
383                and current_stage.password_stage.allow_show_password,
384                "show_source_labels": current_stage.show_source_labels,
385                "flow_designation": self.executor.flow.designation,
386                "enable_remember_me": current_stage.enable_remember_me,
387                "passkey_challenge": self.get_passkey_challenge(),
388            }
389        )
390        # If the user has been redirected to us whilst trying to access an
391        # application, PLAN_CONTEXT_APPLICATION is set in the flow plan
392        if PLAN_CONTEXT_APPLICATION in self.executor.plan.context:
393            app: Application = self.executor.plan.context.get(
394                PLAN_CONTEXT_APPLICATION, Application()
395            )
396            challenge.initial_data["application_pre"] = app.name
397            if not app.meta_hide and (launch_url := app.get_launch_url()):
398                challenge.initial_data["application_pre_launch"] = launch_url
399        if (
400            PLAN_CONTEXT_DEVICE in self.executor.plan.context
401            and PLAN_CONTEXT_DEVICE_AUTH_TOKEN in self.executor.plan.context
402        ):
403            challenge.initial_data["application_pre"] = self.executor.plan.context.get(
404                PLAN_CONTEXT_DEVICE, Device()
405            ).name
406        get_qs = self.request.session.get(SESSION_KEY_GET, self.request.GET)
407        # Check for related enrollment and recovery flow, add URL to view
408        if current_stage.enrollment_flow:
409            challenge.initial_data["enroll_url"] = reverse_with_qs(
410                "authentik_core:if-flow",
411                query=get_qs,
412                kwargs={"flow_slug": current_stage.enrollment_flow.slug},
413            )
414        if current_stage.recovery_flow:
415            challenge.initial_data["recovery_url"] = reverse_with_qs(
416                "authentik_core:if-flow",
417                query=get_qs,
418                kwargs={"flow_slug": current_stage.recovery_flow.slug},
419            )
420        if current_stage.passwordless_flow:
421            challenge.initial_data["passwordless_url"] = reverse_with_qs(
422                "authentik_core:if-flow",
423                query=get_qs,
424                kwargs={"flow_slug": current_stage.passwordless_flow.slug},
425            )
426
427        # Check all enabled source, add them if they have a UI Login button.
428        ui_sources = []
429        sources: list[Source] = (
430            current_stage.sources.filter(enabled=True)
431            .order_by("name")
432            .select_subclasses(*login_capable_source_subclasses())
433        )
434        for source in sources:
435            ui_login_button = source.ui_login_button(self.request)
436            if ui_login_button:
437                button = asdict(ui_login_button)
438                source_challenge = ui_login_button.challenge
439                source_challenge.is_valid()
440                button["challenge"] = source_challenge.data
441                ui_sources.append(button)
442        challenge.initial_data["sources"] = ui_sources
443
444        # Pre-fill username from login_hint unless user clicked "Not you?"
445        if prefill := self.executor.plan.context.get(PLAN_CONTEXT_PENDING_USER_IDENTIFIER):
446            challenge.initial_data["pending_user_identifier"] = prefill
447
448        return challenge
449
450    def challenge_valid(self, response: IdentificationChallengeResponse) -> HttpResponse:
451        # The conditional-UI challenge was answered or is no longer needed. Don't carry it into
452        # a later authenticator validation stage that uses the same plan context key.
453        self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
454        self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = response.pre_user
455        current_stage: IdentificationStage = self.executor.current_stage
456
457        # Handle passkey authentication
458        if response.passkey_device:
459            self.logger.debug("Passkey authentication successful", user=response.pre_user)
460            self.executor.plan.context[PLAN_CONTEXT_METHOD] = "auth_webauthn_pwl"
461            self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
462            self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].update(
463                {
464                    "device": response.passkey_device,
465                    "device_type": response.passkey_device.device_type,
466                }
467            )
468            # Update device last_used
469            with audit_ignore():
470                response.passkey_device.last_used = now()
471                response.passkey_device.save()
472            return self.executor.stage_ok()
473
474        if not current_stage.show_matched_user:
475            self.executor.plan.context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = (
476                response.validated_data.get("uid_field")
477            )
478        return self.executor.stage_ok()
class LoginChallengeMixin:
64class LoginChallengeMixin:
65    """Base login challenge for Identification stage"""

Base login challenge for Identification stage

def get_login_serializers():
68def get_login_serializers():
69    mapping = {
70        RedirectChallenge().fields["component"].default: RedirectChallenge,
71    }
72    for cls in all_subclasses(LoginChallengeMixin):
73        mapping[cls().fields["component"].default] = cls
74    return mapping
@cache
def login_capable_source_subclasses() -> list[type[authentik.core.models.Source]]:
77@cache
78def login_capable_source_subclasses() -> list[type[Source]]:
79    """Concrete Source subclasses that can render a UI login button.
80
81    ``Source.ui_login_button`` returns None, so a source only reaches the
82    challenge below if its subclass overrides it. Abstract subclasses are skipped
83    because they have no table to join against.
84    """
85    return [
86        source_type
87        for source_type in all_subclasses(Source)
88        if not source_type._meta.abstract
89        and source_type.ui_login_button is not Source.ui_login_button
90    ]

Concrete Source subclasses that can render a UI login button.

Source.ui_login_button returns None, so a source only reaches the challenge below if its subclass overrides it. Abstract subclasses are skipped because they have no table to join against.

@extend_schema_field(PolymorphicProxySerializer(component_name='LoginChallengeTypes', serializers=get_login_serializers, resource_type_field_name='component'))
class ChallengeDictWrapper(rest_framework.fields.DictField):
 93@extend_schema_field(
 94    PolymorphicProxySerializer(
 95        component_name="LoginChallengeTypes",
 96        serializers=get_login_serializers,
 97        resource_type_field_name="component",
 98    )
 99)
100class ChallengeDictWrapper(DictField):
101    """Wrapper around DictField that annotates itself as challenge proxy"""

Wrapper around DictField that annotates itself as challenge proxy

class LoginSourceSerializer(authentik.core.api.utils.PassiveSerializer):
104class LoginSourceSerializer(PassiveSerializer):
105    """Serializer for Login buttons of sources"""
106
107    name = CharField()
108    icon_url = CharField(required=False, allow_null=True)
109    icon_themed_urls = ThemedUrlsSerializer(required=False, allow_null=True)
110    promoted = BooleanField(default=False)
111
112    challenge = ChallengeDictWrapper()

Serializer for Login buttons of sources

name
icon_url
icon_themed_urls
promoted
challenge
class IdentificationChallenge(authentik.flows.challenge.Challenge):
115class IdentificationChallenge(Challenge):
116    """Identification challenges with all UI elements"""
117
118    user_fields = ListField(child=CharField(), allow_empty=True, allow_null=True)
119    pending_user_identifier = CharField(required=False, allow_null=True)
120
121    password_fields = BooleanField()
122    allow_show_password = BooleanField(default=False)
123    application_pre = CharField(required=False)
124    application_pre_launch = CharField(required=False)
125    flow_designation = ChoiceField(FlowDesignation.choices)
126    captcha_stage = CaptchaChallenge(required=False, allow_null=True)
127
128    enroll_url = CharField(required=False)
129    recovery_url = CharField(required=False)
130    passwordless_url = CharField(required=False)
131    primary_action = CharField()
132    sources = LoginSourceSerializer(many=True, required=False)
133    show_source_labels = BooleanField()
134    enable_remember_me = BooleanField(required=False, default=True)
135
136    passkey_challenge = JSONDictField(required=False, allow_null=True)
137
138    component = CharField(default="ak-stage-identification")

Identification challenges with all UI elements

user_fields
pending_user_identifier
password_fields
allow_show_password
application_pre
application_pre_launch
flow_designation
captcha_stage
enroll_url
recovery_url
passwordless_url
primary_action
sources
show_source_labels
enable_remember_me
passkey_challenge
component
class IdentificationChallengeResponse(authentik.flows.challenge.ChallengeResponse):
141class IdentificationChallengeResponse(ChallengeResponse):
142    """Identification challenge"""
143
144    uid_field = CharField(required=False, allow_blank=True, allow_null=True)
145    password = CharField(required=False, allow_blank=True, allow_null=True)
146    captcha_token = CharField(required=False, allow_blank=True, allow_null=True)
147    passkey = JSONDictField(required=False, allow_null=True)
148    component = CharField(default="ak-stage-identification")
149
150    pre_user: User | None = None
151    passkey_device: WebAuthnDevice | None = None
152    lockout: PasswordLockoutResult | None = None
153
154    def _validate_passkey_response(self, passkey: dict) -> WebAuthnDevice:
155        """Validate passkey/WebAuthn response for passwordless authentication"""
156        # Get the webauthn_stage from the current IdentificationStage
157        current_stage: IdentificationStage = IdentificationStage.objects.get(
158            pk=self.stage.executor.current_stage.pk
159        )
160        return validate_challenge_webauthn(
161            passkey, self.stage, self.stage.get_pending_user(), current_stage.webauthn_stage
162        )
163
164    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
165        """Validate that user exists, and optionally their password, captcha token, or passkey"""
166        current_stage: IdentificationStage = self.stage.executor.current_stage
167        client_ip = ClientIPMiddleware.get_client_ip(self.stage.request)
168
169        # Check if this is a passkey authentication
170        passkey = attrs.get("passkey")
171        if passkey:
172            device = self._validate_passkey_response(passkey)
173            self.passkey_device = device
174            self.pre_user = device.user
175            # Set backend so password stage policy knows user is already authenticated
176            self.pre_user.backend = class_to_path(IdentificationStageView)
177            return attrs
178
179        # Standard username/password flow
180        uid_field = attrs.get("uid_field")
181        if not uid_field:
182            raise ValidationError(_("No identification data provided."))
183
184        pre_user = self.stage.get_user(uid_field)
185        if not pre_user:
186            with active_tracer().start_span(
187                op="authentik.stages.identification.validate_invalid_wait",
188                name="Sleep random time on invalid user identifier",
189            ):
190                # hash a random password on invalid identifier, same as with a valid identifier
191                make_password(make_password(None))
192            # Log in a similar format to Event.new(), but we don't want to create an event here
193            # as this stage is mostly used by unauthenticated users with very high rate limits
194            self.stage.logger.info(
195                "invalid_login",
196                identifier=uid_field,
197                client_ip=client_ip,
198                action="invalid_identifier",
199                context={
200                    "stage": sanitize_item(self.stage),
201                },
202            )
203            identification_failed.send(sender=self, request=self.stage.request, uid_field=uid_field)
204            # We set the pending_user even on failure so it's part of the context, even
205            # when the input is invalid
206            # This is so its part of the current flow plan, and on flow restart can be kept, and
207            # policies can be applied.
208            self.stage.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = User(
209                username=uid_field,
210                email=uid_field,
211            )
212            self.pre_user = self.stage.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
213            if not current_stage.show_matched_user:
214                self.stage.executor.plan.context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = uid_field
215            # when `pretend` is enabled, continue regardless
216            if current_stage.pretend_user_exists and not current_stage.password_stage:
217                return attrs
218            raise ValidationError(_("Failed to authenticate."))
219        self.pre_user = pre_user
220
221        # Captcha check
222        if captcha_stage := current_stage.captcha_stage:
223            captcha_token = attrs.get("captcha_token", None)
224            if not captcha_token:
225                self.stage.logger.warning("Token not set for captcha attempt")
226            try:
227                verify_captcha_token(
228                    captcha_stage,
229                    captcha_token,
230                    client_ip,
231                    key=self.stage.executor.plan.context.get(PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY),
232                )
233            except ValidationError:
234                raise ValidationError(_("Failed to authenticate.")) from None
235
236        # Password check
237        if current_stage.password_stage:
238            self._validate_password(current_stage, attrs.get("password", None))
239        return attrs
240
241    def _validate_password(self, current_stage: IdentificationStage, password: str | None):
242        """Authenticate the pre-identified user's password against the embedded stage"""
243        if not password:
244            self.stage.logger.warning("Password not set for ident+auth attempt")
245        try:
246            with active_tracer().start_span(
247                op="authentik.stages.identification.authenticate",
248                name="User authenticate call (combo stage)",
249            ):
250                user = authenticate(
251                    self.stage.request,
252                    current_stage.password_stage.backends,
253                    current_stage,
254                    username=self.pre_user.username,
255                    password=password,
256                )
257            result = PasswordLockout(current_stage.password_stage, self.stage.request).apply(
258                self.pre_user, user, self.stage.executor.plan.context
259            )
260            self.lockout = result
261            if not result.user:
262                error = _("Failed to authenticate.")
263                if result.last_attempt:
264                    error = current_stage.password_stage.last_attempt_warning_message or error
265                raise ValidationError(error)
266            self.pre_user = result.user
267        except PermissionDenied as exc:
268            raise ValidationError(str(exc)) from exc

Identification challenge

uid_field
password
captcha_token
passkey
component
pre_user: authentik.core.models.User | None = None
def validate(self, attrs: dict[str, typing.Any]) -> dict[str, typing.Any]:
164    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
165        """Validate that user exists, and optionally their password, captcha token, or passkey"""
166        current_stage: IdentificationStage = self.stage.executor.current_stage
167        client_ip = ClientIPMiddleware.get_client_ip(self.stage.request)
168
169        # Check if this is a passkey authentication
170        passkey = attrs.get("passkey")
171        if passkey:
172            device = self._validate_passkey_response(passkey)
173            self.passkey_device = device
174            self.pre_user = device.user
175            # Set backend so password stage policy knows user is already authenticated
176            self.pre_user.backend = class_to_path(IdentificationStageView)
177            return attrs
178
179        # Standard username/password flow
180        uid_field = attrs.get("uid_field")
181        if not uid_field:
182            raise ValidationError(_("No identification data provided."))
183
184        pre_user = self.stage.get_user(uid_field)
185        if not pre_user:
186            with active_tracer().start_span(
187                op="authentik.stages.identification.validate_invalid_wait",
188                name="Sleep random time on invalid user identifier",
189            ):
190                # hash a random password on invalid identifier, same as with a valid identifier
191                make_password(make_password(None))
192            # Log in a similar format to Event.new(), but we don't want to create an event here
193            # as this stage is mostly used by unauthenticated users with very high rate limits
194            self.stage.logger.info(
195                "invalid_login",
196                identifier=uid_field,
197                client_ip=client_ip,
198                action="invalid_identifier",
199                context={
200                    "stage": sanitize_item(self.stage),
201                },
202            )
203            identification_failed.send(sender=self, request=self.stage.request, uid_field=uid_field)
204            # We set the pending_user even on failure so it's part of the context, even
205            # when the input is invalid
206            # This is so its part of the current flow plan, and on flow restart can be kept, and
207            # policies can be applied.
208            self.stage.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = User(
209                username=uid_field,
210                email=uid_field,
211            )
212            self.pre_user = self.stage.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
213            if not current_stage.show_matched_user:
214                self.stage.executor.plan.context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = uid_field
215            # when `pretend` is enabled, continue regardless
216            if current_stage.pretend_user_exists and not current_stage.password_stage:
217                return attrs
218            raise ValidationError(_("Failed to authenticate."))
219        self.pre_user = pre_user
220
221        # Captcha check
222        if captcha_stage := current_stage.captcha_stage:
223            captcha_token = attrs.get("captcha_token", None)
224            if not captcha_token:
225                self.stage.logger.warning("Token not set for captcha attempt")
226            try:
227                verify_captcha_token(
228                    captcha_stage,
229                    captcha_token,
230                    client_ip,
231                    key=self.stage.executor.plan.context.get(PLAN_CONTEXT_CAPTCHA_PRIVATE_KEY),
232                )
233            except ValidationError:
234                raise ValidationError(_("Failed to authenticate.")) from None
235
236        # Password check
237        if current_stage.password_stage:
238            self._validate_password(current_stage, attrs.get("password", None))
239        return attrs

Validate that user exists, and optionally their password, captcha token, or passkey

class IdentificationStageView(authentik.flows.stage.ChallengeStageView):
271class IdentificationStageView(ChallengeStageView):
272    """Form to identify the user"""
273
274    response_class = IdentificationChallengeResponse
275
276    def challenge_invalid(self, response: IdentificationChallengeResponse) -> HttpResponse:
277        """Stop the flow once its embedded password stage reaches its lockout."""
278        current_stage: IdentificationStage = self.executor.current_stage
279        if current_stage.password_stage and response.lockout and response.lockout.lockout_reached:
280            return self.executor.stage_invalid(
281                current_stage.password_stage.lockout_message or _("Failed to authenticate.")
282            )
283        return super().challenge_invalid(response)
284
285    def get_user(self, uid_value: str) -> User | None:
286        """Find user instance. Returns None if no user was found."""
287        current_stage: IdentificationStage = self.executor.current_stage
288        query = Q()
289        for search_field in current_stage.user_fields:
290            model_field = {
291                "email": "email",
292                "username": "username",
293                "upn": "attributes__upn",
294            }[search_field]
295            if current_stage.case_insensitive_matching:
296                model_field += "__iexact"
297            else:
298                model_field += "__exact"
299            query |= Q(**{model_field: uid_value})
300        if not query:
301            self.logger.debug("Empty user query", query=query)
302            return None
303        user = User.objects.filter(query).first()
304        if user:
305            self.logger.debug("Found user", user=user.username, query=query)
306            return user
307        return None
308
309    def get_primary_action(self) -> str:
310        """Get the primary action label for this stage"""
311        if self.executor.flow.designation == FlowDesignation.AUTHENTICATION:
312            return _("Log in")
313        return _("Continue")
314
315    def get_passkey_challenge(self) -> dict | None:
316        """Generate a WebAuthn challenge for passkey/conditional UI authentication"""
317        # Refresh from DB to get the latest configuration
318        current_stage: IdentificationStage = IdentificationStage.objects.get(
319            pk=self.executor.current_stage.pk
320        )
321        if not current_stage.webauthn_stage:
322            self.logger.debug("No webauthn_stage configured")
323            return None
324        challenge = get_webauthn_challenge_without_user(self, current_stage.webauthn_stage)
325        self.logger.debug("Generated passkey challenge", challenge=challenge)
326        return challenge
327
328    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
329        """Check for existing pending user identifier and skip stage if possible"""
330        current_stage: IdentificationStage = self.executor.current_stage
331        pending_user_identifier = self.executor.plan.context.get(
332            PLAN_CONTEXT_PENDING_USER_IDENTIFIER
333        )
334
335        if not pending_user_identifier:
336            return super().get(request, *args, **kwargs)
337
338        # Only skip if this is a "simple" identification stage with no extra features
339        can_skip = (
340            not current_stage.password_stage
341            and not current_stage.captcha_stage
342            and not current_stage.webauthn_stage
343            and not self.executor.current_binding.policies.exists()
344        )
345
346        if can_skip:
347            # Use the normal validation flow (handles timing protection, logging, signals)
348            response = IdentificationChallengeResponse(
349                data={"uid_field": pending_user_identifier},
350                stage=self,
351            )
352            if response.is_valid():
353                return self.challenge_valid(response)
354            # Validation failed (user doesn't exist and pretend_user_exists is off)
355            # Don't pre-fill invalid username, fall through to show the challenge
356            self.executor.plan.context.pop(PLAN_CONTEXT_PENDING_USER_IDENTIFIER, None)
357
358        # Can't skip - just pre-fill the username field
359        return super().get(request, *args, **kwargs)
360
361    def get_challenge(self) -> Challenge:
362        current_stage: IdentificationStage = self.executor.current_stage
363        challenge = IdentificationChallenge(
364            data={
365                "component": "ak-stage-identification",
366                "primary_action": self.get_primary_action(),
367                "user_fields": current_stage.user_fields,
368                "password_fields": bool(current_stage.password_stage),
369                "captcha_stage": (
370                    {
371                        "js_url": current_stage.captcha_stage.js_url,
372                        "site_key": self.executor.plan.context.get(
373                            PLAN_CONTEXT_CAPTCHA_SITE_KEY,
374                            current_stage.captcha_stage.public_key,
375                        ),
376                        "interactive": current_stage.captcha_stage.interactive,
377                        "pending_user": "",
378                        "pending_user_avatar": DEFAULT_AVATAR,
379                    }
380                    if current_stage.captcha_stage
381                    else None
382                ),
383                "allow_show_password": bool(current_stage.password_stage)
384                and current_stage.password_stage.allow_show_password,
385                "show_source_labels": current_stage.show_source_labels,
386                "flow_designation": self.executor.flow.designation,
387                "enable_remember_me": current_stage.enable_remember_me,
388                "passkey_challenge": self.get_passkey_challenge(),
389            }
390        )
391        # If the user has been redirected to us whilst trying to access an
392        # application, PLAN_CONTEXT_APPLICATION is set in the flow plan
393        if PLAN_CONTEXT_APPLICATION in self.executor.plan.context:
394            app: Application = self.executor.plan.context.get(
395                PLAN_CONTEXT_APPLICATION, Application()
396            )
397            challenge.initial_data["application_pre"] = app.name
398            if not app.meta_hide and (launch_url := app.get_launch_url()):
399                challenge.initial_data["application_pre_launch"] = launch_url
400        if (
401            PLAN_CONTEXT_DEVICE in self.executor.plan.context
402            and PLAN_CONTEXT_DEVICE_AUTH_TOKEN in self.executor.plan.context
403        ):
404            challenge.initial_data["application_pre"] = self.executor.plan.context.get(
405                PLAN_CONTEXT_DEVICE, Device()
406            ).name
407        get_qs = self.request.session.get(SESSION_KEY_GET, self.request.GET)
408        # Check for related enrollment and recovery flow, add URL to view
409        if current_stage.enrollment_flow:
410            challenge.initial_data["enroll_url"] = reverse_with_qs(
411                "authentik_core:if-flow",
412                query=get_qs,
413                kwargs={"flow_slug": current_stage.enrollment_flow.slug},
414            )
415        if current_stage.recovery_flow:
416            challenge.initial_data["recovery_url"] = reverse_with_qs(
417                "authentik_core:if-flow",
418                query=get_qs,
419                kwargs={"flow_slug": current_stage.recovery_flow.slug},
420            )
421        if current_stage.passwordless_flow:
422            challenge.initial_data["passwordless_url"] = reverse_with_qs(
423                "authentik_core:if-flow",
424                query=get_qs,
425                kwargs={"flow_slug": current_stage.passwordless_flow.slug},
426            )
427
428        # Check all enabled source, add them if they have a UI Login button.
429        ui_sources = []
430        sources: list[Source] = (
431            current_stage.sources.filter(enabled=True)
432            .order_by("name")
433            .select_subclasses(*login_capable_source_subclasses())
434        )
435        for source in sources:
436            ui_login_button = source.ui_login_button(self.request)
437            if ui_login_button:
438                button = asdict(ui_login_button)
439                source_challenge = ui_login_button.challenge
440                source_challenge.is_valid()
441                button["challenge"] = source_challenge.data
442                ui_sources.append(button)
443        challenge.initial_data["sources"] = ui_sources
444
445        # Pre-fill username from login_hint unless user clicked "Not you?"
446        if prefill := self.executor.plan.context.get(PLAN_CONTEXT_PENDING_USER_IDENTIFIER):
447            challenge.initial_data["pending_user_identifier"] = prefill
448
449        return challenge
450
451    def challenge_valid(self, response: IdentificationChallengeResponse) -> HttpResponse:
452        # The conditional-UI challenge was answered or is no longer needed. Don't carry it into
453        # a later authenticator validation stage that uses the same plan context key.
454        self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
455        self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = response.pre_user
456        current_stage: IdentificationStage = self.executor.current_stage
457
458        # Handle passkey authentication
459        if response.passkey_device:
460            self.logger.debug("Passkey authentication successful", user=response.pre_user)
461            self.executor.plan.context[PLAN_CONTEXT_METHOD] = "auth_webauthn_pwl"
462            self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
463            self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].update(
464                {
465                    "device": response.passkey_device,
466                    "device_type": response.passkey_device.device_type,
467                }
468            )
469            # Update device last_used
470            with audit_ignore():
471                response.passkey_device.last_used = now()
472                response.passkey_device.save()
473            return self.executor.stage_ok()
474
475        if not current_stage.show_matched_user:
476            self.executor.plan.context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = (
477                response.validated_data.get("uid_field")
478            )
479        return self.executor.stage_ok()

Form to identify the user

response_class = <class 'IdentificationChallengeResponse'>
def challenge_invalid( self, response: IdentificationChallengeResponse) -> django.http.response.HttpResponse:
276    def challenge_invalid(self, response: IdentificationChallengeResponse) -> HttpResponse:
277        """Stop the flow once its embedded password stage reaches its lockout."""
278        current_stage: IdentificationStage = self.executor.current_stage
279        if current_stage.password_stage and response.lockout and response.lockout.lockout_reached:
280            return self.executor.stage_invalid(
281                current_stage.password_stage.lockout_message or _("Failed to authenticate.")
282            )
283        return super().challenge_invalid(response)

Stop the flow once its embedded password stage reaches its lockout.

def get_user(self, uid_value: str) -> authentik.core.models.User | None:
285    def get_user(self, uid_value: str) -> User | None:
286        """Find user instance. Returns None if no user was found."""
287        current_stage: IdentificationStage = self.executor.current_stage
288        query = Q()
289        for search_field in current_stage.user_fields:
290            model_field = {
291                "email": "email",
292                "username": "username",
293                "upn": "attributes__upn",
294            }[search_field]
295            if current_stage.case_insensitive_matching:
296                model_field += "__iexact"
297            else:
298                model_field += "__exact"
299            query |= Q(**{model_field: uid_value})
300        if not query:
301            self.logger.debug("Empty user query", query=query)
302            return None
303        user = User.objects.filter(query).first()
304        if user:
305            self.logger.debug("Found user", user=user.username, query=query)
306            return user
307        return None

Find user instance. Returns None if no user was found.

def get_primary_action(self) -> str:
309    def get_primary_action(self) -> str:
310        """Get the primary action label for this stage"""
311        if self.executor.flow.designation == FlowDesignation.AUTHENTICATION:
312            return _("Log in")
313        return _("Continue")

Get the primary action label for this stage

def get_passkey_challenge(self) -> dict | None:
315    def get_passkey_challenge(self) -> dict | None:
316        """Generate a WebAuthn challenge for passkey/conditional UI authentication"""
317        # Refresh from DB to get the latest configuration
318        current_stage: IdentificationStage = IdentificationStage.objects.get(
319            pk=self.executor.current_stage.pk
320        )
321        if not current_stage.webauthn_stage:
322            self.logger.debug("No webauthn_stage configured")
323            return None
324        challenge = get_webauthn_challenge_without_user(self, current_stage.webauthn_stage)
325        self.logger.debug("Generated passkey challenge", challenge=challenge)
326        return challenge

Generate a WebAuthn challenge for passkey/conditional UI authentication

def get( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
328    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
329        """Check for existing pending user identifier and skip stage if possible"""
330        current_stage: IdentificationStage = self.executor.current_stage
331        pending_user_identifier = self.executor.plan.context.get(
332            PLAN_CONTEXT_PENDING_USER_IDENTIFIER
333        )
334
335        if not pending_user_identifier:
336            return super().get(request, *args, **kwargs)
337
338        # Only skip if this is a "simple" identification stage with no extra features
339        can_skip = (
340            not current_stage.password_stage
341            and not current_stage.captcha_stage
342            and not current_stage.webauthn_stage
343            and not self.executor.current_binding.policies.exists()
344        )
345
346        if can_skip:
347            # Use the normal validation flow (handles timing protection, logging, signals)
348            response = IdentificationChallengeResponse(
349                data={"uid_field": pending_user_identifier},
350                stage=self,
351            )
352            if response.is_valid():
353                return self.challenge_valid(response)
354            # Validation failed (user doesn't exist and pretend_user_exists is off)
355            # Don't pre-fill invalid username, fall through to show the challenge
356            self.executor.plan.context.pop(PLAN_CONTEXT_PENDING_USER_IDENTIFIER, None)
357
358        # Can't skip - just pre-fill the username field
359        return super().get(request, *args, **kwargs)

Check for existing pending user identifier and skip stage if possible

def get_challenge(self) -> authentik.flows.challenge.Challenge:
361    def get_challenge(self) -> Challenge:
362        current_stage: IdentificationStage = self.executor.current_stage
363        challenge = IdentificationChallenge(
364            data={
365                "component": "ak-stage-identification",
366                "primary_action": self.get_primary_action(),
367                "user_fields": current_stage.user_fields,
368                "password_fields": bool(current_stage.password_stage),
369                "captcha_stage": (
370                    {
371                        "js_url": current_stage.captcha_stage.js_url,
372                        "site_key": self.executor.plan.context.get(
373                            PLAN_CONTEXT_CAPTCHA_SITE_KEY,
374                            current_stage.captcha_stage.public_key,
375                        ),
376                        "interactive": current_stage.captcha_stage.interactive,
377                        "pending_user": "",
378                        "pending_user_avatar": DEFAULT_AVATAR,
379                    }
380                    if current_stage.captcha_stage
381                    else None
382                ),
383                "allow_show_password": bool(current_stage.password_stage)
384                and current_stage.password_stage.allow_show_password,
385                "show_source_labels": current_stage.show_source_labels,
386                "flow_designation": self.executor.flow.designation,
387                "enable_remember_me": current_stage.enable_remember_me,
388                "passkey_challenge": self.get_passkey_challenge(),
389            }
390        )
391        # If the user has been redirected to us whilst trying to access an
392        # application, PLAN_CONTEXT_APPLICATION is set in the flow plan
393        if PLAN_CONTEXT_APPLICATION in self.executor.plan.context:
394            app: Application = self.executor.plan.context.get(
395                PLAN_CONTEXT_APPLICATION, Application()
396            )
397            challenge.initial_data["application_pre"] = app.name
398            if not app.meta_hide and (launch_url := app.get_launch_url()):
399                challenge.initial_data["application_pre_launch"] = launch_url
400        if (
401            PLAN_CONTEXT_DEVICE in self.executor.plan.context
402            and PLAN_CONTEXT_DEVICE_AUTH_TOKEN in self.executor.plan.context
403        ):
404            challenge.initial_data["application_pre"] = self.executor.plan.context.get(
405                PLAN_CONTEXT_DEVICE, Device()
406            ).name
407        get_qs = self.request.session.get(SESSION_KEY_GET, self.request.GET)
408        # Check for related enrollment and recovery flow, add URL to view
409        if current_stage.enrollment_flow:
410            challenge.initial_data["enroll_url"] = reverse_with_qs(
411                "authentik_core:if-flow",
412                query=get_qs,
413                kwargs={"flow_slug": current_stage.enrollment_flow.slug},
414            )
415        if current_stage.recovery_flow:
416            challenge.initial_data["recovery_url"] = reverse_with_qs(
417                "authentik_core:if-flow",
418                query=get_qs,
419                kwargs={"flow_slug": current_stage.recovery_flow.slug},
420            )
421        if current_stage.passwordless_flow:
422            challenge.initial_data["passwordless_url"] = reverse_with_qs(
423                "authentik_core:if-flow",
424                query=get_qs,
425                kwargs={"flow_slug": current_stage.passwordless_flow.slug},
426            )
427
428        # Check all enabled source, add them if they have a UI Login button.
429        ui_sources = []
430        sources: list[Source] = (
431            current_stage.sources.filter(enabled=True)
432            .order_by("name")
433            .select_subclasses(*login_capable_source_subclasses())
434        )
435        for source in sources:
436            ui_login_button = source.ui_login_button(self.request)
437            if ui_login_button:
438                button = asdict(ui_login_button)
439                source_challenge = ui_login_button.challenge
440                source_challenge.is_valid()
441                button["challenge"] = source_challenge.data
442                ui_sources.append(button)
443        challenge.initial_data["sources"] = ui_sources
444
445        # Pre-fill username from login_hint unless user clicked "Not you?"
446        if prefill := self.executor.plan.context.get(PLAN_CONTEXT_PENDING_USER_IDENTIFIER):
447            challenge.initial_data["pending_user_identifier"] = prefill
448
449        return challenge

Return the challenge that the client should solve

def challenge_valid( self, response: IdentificationChallengeResponse) -> django.http.response.HttpResponse:
451    def challenge_valid(self, response: IdentificationChallengeResponse) -> HttpResponse:
452        # The conditional-UI challenge was answered or is no longer needed. Don't carry it into
453        # a later authenticator validation stage that uses the same plan context key.
454        self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
455        self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = response.pre_user
456        current_stage: IdentificationStage = self.executor.current_stage
457
458        # Handle passkey authentication
459        if response.passkey_device:
460            self.logger.debug("Passkey authentication successful", user=response.pre_user)
461            self.executor.plan.context[PLAN_CONTEXT_METHOD] = "auth_webauthn_pwl"
462            self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
463            self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].update(
464                {
465                    "device": response.passkey_device,
466                    "device_type": response.passkey_device.device_type,
467                }
468            )
469            # Update device last_used
470            with audit_ignore():
471                response.passkey_device.last_used = now()
472                response.passkey_device.save()
473            return self.executor.stage_ok()
474
475        if not current_stage.show_matched_user:
476            self.executor.plan.context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = (
477                response.validated_data.get("uid_field")
478            )
479        return self.executor.stage_ok()

Callback when the challenge has the correct format