authentik.stages.authenticator_webauthn.stage

WebAuthn stage

  1"""WebAuthn stage"""
  2
  3from dataclasses import dataclass
  4from uuid import UUID
  5
  6from cryptography.hazmat.primitives.serialization import Encoding
  7from cryptography.x509 import load_der_x509_certificate
  8from django.http import HttpRequest, HttpResponse
  9from django.http.request import QueryDict
 10from django.utils.translation import gettext_lazy as _
 11from rest_framework.fields import CharField
 12from rest_framework.serializers import ValidationError
 13from webauthn.helpers.base64url_to_bytes import base64url_to_bytes
 14from webauthn.helpers.bytes_to_base64url import bytes_to_base64url
 15from webauthn.helpers.exceptions import WebAuthnException
 16from webauthn.helpers.options_to_json_dict import options_to_json_dict
 17from webauthn.helpers.parse_attestation_object import parse_attestation_object
 18from webauthn.helpers.structs import (
 19    AttestationConveyancePreference,
 20    AuthenticatorAttachment,
 21    AuthenticatorSelectionCriteria,
 22    PublicKeyCredentialCreationOptions,
 23    PublicKeyCredentialDescriptor,
 24    PublicKeyCredentialHint,
 25    ResidentKeyRequirement,
 26    UserVerificationRequirement,
 27)
 28from webauthn.registration.generate_registration_options import generate_registration_options
 29from webauthn.registration.verify_registration_response import (
 30    VerifiedRegistration,
 31    verify_registration_response,
 32)
 33
 34from authentik.core.api.utils import JSONDictField
 35from authentik.core.models import User
 36from authentik.crypto.models import fingerprint_sha256
 37from authentik.flows.challenge import (
 38    Challenge,
 39    ChallengeResponse,
 40    WithUserInfoChallenge,
 41)
 42from authentik.flows.stage import ChallengeStageView
 43from authentik.stages.authenticator_webauthn.algorithms import supported_pub_key_algs
 44from authentik.stages.authenticator_webauthn.models import (
 45    UNKNOWN_DEVICE_TYPE_AAGUID,
 46    AuthenticatorWebAuthnStage,
 47    WebAuthnDevice,
 48    WebAuthnDeviceType,
 49)
 50from authentik.stages.authenticator_webauthn.utils import get_expected_origins, get_rp_id
 51
 52PLAN_CONTEXT_WEBAUTHN_CHALLENGE = "goauthentik.io/stages/authenticator_webauthn/challenge"
 53PLAN_CONTEXT_WEBAUTHN_ATTEMPT = "goauthentik.io/stages/authenticator_webauthn/attempt"
 54
 55
 56@dataclass
 57class VerifiedRegistrationData:
 58    registration: VerifiedRegistration
 59    attest_cert: str | None = None
 60    attest_cert_fingerprint: str | None = None
 61
 62
 63class AuthenticatorWebAuthnChallenge(WithUserInfoChallenge):
 64    """WebAuthn Challenge"""
 65
 66    registration = JSONDictField()
 67    component = CharField(default="ak-stage-authenticator-webauthn")
 68
 69
 70class AuthenticatorWebAuthnChallengeResponse(ChallengeResponse):
 71    """WebAuthn Challenge response"""
 72
 73    response = JSONDictField()
 74    component = CharField(default="ak-stage-authenticator-webauthn")
 75
 76    request: HttpRequest
 77    user: User
 78
 79    def validate_response(self, response: dict) -> VerifiedRegistrationData:
 80        """Validate webauthn challenge response"""
 81        challenge = self.stage.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE]
 82        stage: AuthenticatorWebAuthnStage = self.stage.executor.current_stage
 83
 84        try:
 85            registration: VerifiedRegistration = verify_registration_response(
 86                credential=response,
 87                expected_challenge=challenge,
 88                expected_rp_id=get_rp_id(self.request),
 89                expected_origin=get_expected_origins(
 90                    self.request, stage.additional_accepted_origins
 91                ),
 92                supported_pub_key_algs=supported_pub_key_algs(),
 93            )
 94        # py_webauthn does not wrap cryptography's ValueError when an attestation certificate
 95        # fails to parse, which happens with authenticators that ship non-DER certificates
 96        except (WebAuthnException, ValueError) as exc:
 97            self.stage.logger.warning("registration failed", exc=exc)
 98            raise ValidationError(
 99                "Registration failed. Please contact your administrator."
100            ) from None
101
102        registration_data = VerifiedRegistrationData(registration)
103
104        att_obj = parse_attestation_object(registration.attestation_object)
105        if (
106            att_obj
107            and att_obj.att_stmt
108            and att_obj.att_stmt.x5c is not None
109            and len(att_obj.att_stmt.x5c) > 0
110        ):
111            # android-key attestation verifies with OpenSSL, which accepts certificates that
112            # cryptography rejects. The registration is valid, so only skip storing the certificate
113            try:
114                cert = load_der_x509_certificate(att_obj.att_stmt.x5c[0])
115            except ValueError as exc:
116                self.stage.logger.warning("failed to parse attestation certificate", exc=exc)
117            else:
118                registration_data.attest_cert = cert.public_bytes(
119                    encoding=Encoding.PEM,
120                ).decode("utf-8")
121                registration_data.attest_cert_fingerprint = fingerprint_sha256(cert)
122
123        if WebAuthnDevice.objects.filter(
124            credential_id=bytes_to_base64url(registration.credential_id)
125        ).exists():
126            raise ValidationError("Credential ID already exists.")
127
128        aaguid = registration.aaguid
129        allowed_aaguids = stage.device_type_restrictions.values_list("aaguid", flat=True)
130        if allowed_aaguids.exists():
131            invalid_error = ValidationError(
132                _("Invalid device type. Contact your {brand} administrator for help.").format(
133                    brand=self.stage.request.brand.branding_title
134                )
135            )
136            # If there are any restrictions set and we didn't get an aaguid, invalid
137            if not aaguid:
138                raise invalid_error
139            # If one of the restrictions is the "special" unknown device type UUID
140            # but we do have a device type for the given aaguid, invalid
141            if (
142                UUID(UNKNOWN_DEVICE_TYPE_AAGUID) in allowed_aaguids
143                and not WebAuthnDeviceType.objects.filter(aaguid=aaguid).exists()
144            ):
145                return registration_data
146            # Otherwise just check if the given aaguid is in the allowed aaguids
147            if UUID(aaguid) not in allowed_aaguids:
148                raise invalid_error
149        return registration_data
150
151
152class AuthenticatorWebAuthnStageView(ChallengeStageView):
153    """WebAuthn stage"""
154
155    response_class = AuthenticatorWebAuthnChallengeResponse
156
157    def get_challenge(self, *args, **kwargs) -> Challenge:
158        stage: AuthenticatorWebAuthnStage = self.executor.current_stage
159        self.executor.plan.context.setdefault(PLAN_CONTEXT_WEBAUTHN_ATTEMPT, 0)
160        # clear flow variables prior to starting a new registration
161        self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
162        user = self.get_pending_user()
163
164        # library accepts none so we store null in the database, but if there is a value
165        # set, cast it to string to ensure it's not a django class
166        authenticator_attachment = stage.authenticator_attachment
167        if authenticator_attachment:
168            authenticator_attachment = AuthenticatorAttachment(str(authenticator_attachment))
169
170        hints = [PublicKeyCredentialHint(h) for h in stage.hints] or None
171
172        # For compatibility with older user agents that don't support hints,
173        # auto-infer authenticatorAttachment from hints when not explicitly set.
174        # https://w3c.github.io/webauthn/#enum-hints
175        if hints and not authenticator_attachment:
176            hint_values = set(stage.hints)
177            cross_platform = {"security-key", "hybrid"}
178            platform = {"client-device"}
179            if hint_values <= cross_platform:
180                authenticator_attachment = AuthenticatorAttachment.CROSS_PLATFORM
181            elif hint_values <= platform:
182                authenticator_attachment = AuthenticatorAttachment.PLATFORM
183
184        rp_id = get_rp_id(self.request)
185
186        # Let the authenticator itself refuse to register a credential it already holds for this
187        # user. Only confirmed devices count; an unconfirmed one is not usable and must not block
188        # re-enrolling the same authenticator.
189        exclude_credentials = [
190            PublicKeyCredentialDescriptor(id=base64url_to_bytes(credential_id))
191            for credential_id in WebAuthnDevice.objects.filter(
192                user=user, rp_id=rp_id, confirmed=True
193            )
194            .order_by("pk")
195            .values_list("credential_id", flat=True)
196        ]
197
198        registration_options: PublicKeyCredentialCreationOptions = generate_registration_options(
199            rp_id=rp_id,
200            rp_name=self.request.brand.branding_title,
201            user_id=user.uid.encode("utf-8"),
202            user_name=user.username,
203            user_display_name=user.name,
204            authenticator_selection=AuthenticatorSelectionCriteria(
205                resident_key=ResidentKeyRequirement(str(stage.resident_key_requirement)),
206                user_verification=UserVerificationRequirement(str(stage.user_verification)),
207                authenticator_attachment=authenticator_attachment,
208            ),
209            attestation=AttestationConveyancePreference.DIRECT,
210            exclude_credentials=exclude_credentials,
211            hints=hints,
212            supported_pub_key_algs=supported_pub_key_algs(),
213        )
214
215        self.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = registration_options.challenge
216        return AuthenticatorWebAuthnChallenge(
217            data={
218                "registration": options_to_json_dict(registration_options),
219            }
220        )
221
222    def get_response_instance(self, data: QueryDict) -> AuthenticatorWebAuthnChallengeResponse:
223        response: AuthenticatorWebAuthnChallengeResponse = super().get_response_instance(data)
224        response.request = self.request
225        response.user = self.get_pending_user()
226        return response
227
228    def challenge_invalid(self, response):
229        stage: AuthenticatorWebAuthnStage = self.executor.current_stage
230        self.executor.plan.context.setdefault(PLAN_CONTEXT_WEBAUTHN_ATTEMPT, 0)
231        self.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_ATTEMPT] += 1
232        if (
233            stage.max_attempts > 0
234            and self.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_ATTEMPT] >= stage.max_attempts
235        ):
236            return self.executor.stage_invalid(
237                _("Exceeded maximum attempts. Contact your {brand} administrator for help.").format(
238                    brand=self.request.brand.branding_title
239                )
240            )
241        return super().challenge_invalid(response)
242
243    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
244        # Webauthn Challenge has already been validated
245        webauthn_credential: VerifiedRegistrationData = response.validated_data["response"]
246        name = "WebAuthn Device"
247        device_type = WebAuthnDeviceType.objects.filter(
248            aaguid=webauthn_credential.registration.aaguid
249        ).first()
250        if device_type and device_type.description:
251            name = device_type.description
252        WebAuthnDevice.objects.create(
253            name=name,
254            user=self.get_pending_user(),
255            public_key=bytes_to_base64url(webauthn_credential.registration.credential_public_key),
256            credential_id=bytes_to_base64url(webauthn_credential.registration.credential_id),
257            sign_count=webauthn_credential.registration.sign_count,
258            rp_id=get_rp_id(self.request),
259            device_type=device_type,
260            aaguid=webauthn_credential.registration.aaguid,
261            attestation_certificate_pem=webauthn_credential.attest_cert,
262            attestation_certificate_fingerprint=webauthn_credential.attest_cert_fingerprint,
263        )
264        # The registration challenge has been answered. Remove it, as the authenticator validation
265        # stage uses the same key and keeps a pending challenge until it's answered
266        self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
267        return self.executor.stage_ok()
PLAN_CONTEXT_WEBAUTHN_CHALLENGE = 'goauthentik.io/stages/authenticator_webauthn/challenge'
PLAN_CONTEXT_WEBAUTHN_ATTEMPT = 'goauthentik.io/stages/authenticator_webauthn/attempt'
@dataclass
class VerifiedRegistrationData:
57@dataclass
58class VerifiedRegistrationData:
59    registration: VerifiedRegistration
60    attest_cert: str | None = None
61    attest_cert_fingerprint: str | None = None
VerifiedRegistrationData( registration: webauthn.registration.verify_registration_response.VerifiedRegistration, attest_cert: str | None = None, attest_cert_fingerprint: str | None = None)
registration: webauthn.registration.verify_registration_response.VerifiedRegistration
attest_cert: str | None = None
attest_cert_fingerprint: str | None = None
class AuthenticatorWebAuthnChallenge(authentik.flows.challenge.WithUserInfoChallenge):
64class AuthenticatorWebAuthnChallenge(WithUserInfoChallenge):
65    """WebAuthn Challenge"""
66
67    registration = JSONDictField()
68    component = CharField(default="ak-stage-authenticator-webauthn")

WebAuthn Challenge

registration
component
class AuthenticatorWebAuthnChallengeResponse(authentik.flows.challenge.ChallengeResponse):
 71class AuthenticatorWebAuthnChallengeResponse(ChallengeResponse):
 72    """WebAuthn Challenge response"""
 73
 74    response = JSONDictField()
 75    component = CharField(default="ak-stage-authenticator-webauthn")
 76
 77    request: HttpRequest
 78    user: User
 79
 80    def validate_response(self, response: dict) -> VerifiedRegistrationData:
 81        """Validate webauthn challenge response"""
 82        challenge = self.stage.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE]
 83        stage: AuthenticatorWebAuthnStage = self.stage.executor.current_stage
 84
 85        try:
 86            registration: VerifiedRegistration = verify_registration_response(
 87                credential=response,
 88                expected_challenge=challenge,
 89                expected_rp_id=get_rp_id(self.request),
 90                expected_origin=get_expected_origins(
 91                    self.request, stage.additional_accepted_origins
 92                ),
 93                supported_pub_key_algs=supported_pub_key_algs(),
 94            )
 95        # py_webauthn does not wrap cryptography's ValueError when an attestation certificate
 96        # fails to parse, which happens with authenticators that ship non-DER certificates
 97        except (WebAuthnException, ValueError) as exc:
 98            self.stage.logger.warning("registration failed", exc=exc)
 99            raise ValidationError(
100                "Registration failed. Please contact your administrator."
101            ) from None
102
103        registration_data = VerifiedRegistrationData(registration)
104
105        att_obj = parse_attestation_object(registration.attestation_object)
106        if (
107            att_obj
108            and att_obj.att_stmt
109            and att_obj.att_stmt.x5c is not None
110            and len(att_obj.att_stmt.x5c) > 0
111        ):
112            # android-key attestation verifies with OpenSSL, which accepts certificates that
113            # cryptography rejects. The registration is valid, so only skip storing the certificate
114            try:
115                cert = load_der_x509_certificate(att_obj.att_stmt.x5c[0])
116            except ValueError as exc:
117                self.stage.logger.warning("failed to parse attestation certificate", exc=exc)
118            else:
119                registration_data.attest_cert = cert.public_bytes(
120                    encoding=Encoding.PEM,
121                ).decode("utf-8")
122                registration_data.attest_cert_fingerprint = fingerprint_sha256(cert)
123
124        if WebAuthnDevice.objects.filter(
125            credential_id=bytes_to_base64url(registration.credential_id)
126        ).exists():
127            raise ValidationError("Credential ID already exists.")
128
129        aaguid = registration.aaguid
130        allowed_aaguids = stage.device_type_restrictions.values_list("aaguid", flat=True)
131        if allowed_aaguids.exists():
132            invalid_error = ValidationError(
133                _("Invalid device type. Contact your {brand} administrator for help.").format(
134                    brand=self.stage.request.brand.branding_title
135                )
136            )
137            # If there are any restrictions set and we didn't get an aaguid, invalid
138            if not aaguid:
139                raise invalid_error
140            # If one of the restrictions is the "special" unknown device type UUID
141            # but we do have a device type for the given aaguid, invalid
142            if (
143                UUID(UNKNOWN_DEVICE_TYPE_AAGUID) in allowed_aaguids
144                and not WebAuthnDeviceType.objects.filter(aaguid=aaguid).exists()
145            ):
146                return registration_data
147            # Otherwise just check if the given aaguid is in the allowed aaguids
148            if UUID(aaguid) not in allowed_aaguids:
149                raise invalid_error
150        return registration_data

WebAuthn Challenge response

response
component
request: django.http.request.HttpRequest
def validate_response( self, response: dict) -> VerifiedRegistrationData:
 80    def validate_response(self, response: dict) -> VerifiedRegistrationData:
 81        """Validate webauthn challenge response"""
 82        challenge = self.stage.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE]
 83        stage: AuthenticatorWebAuthnStage = self.stage.executor.current_stage
 84
 85        try:
 86            registration: VerifiedRegistration = verify_registration_response(
 87                credential=response,
 88                expected_challenge=challenge,
 89                expected_rp_id=get_rp_id(self.request),
 90                expected_origin=get_expected_origins(
 91                    self.request, stage.additional_accepted_origins
 92                ),
 93                supported_pub_key_algs=supported_pub_key_algs(),
 94            )
 95        # py_webauthn does not wrap cryptography's ValueError when an attestation certificate
 96        # fails to parse, which happens with authenticators that ship non-DER certificates
 97        except (WebAuthnException, ValueError) as exc:
 98            self.stage.logger.warning("registration failed", exc=exc)
 99            raise ValidationError(
100                "Registration failed. Please contact your administrator."
101            ) from None
102
103        registration_data = VerifiedRegistrationData(registration)
104
105        att_obj = parse_attestation_object(registration.attestation_object)
106        if (
107            att_obj
108            and att_obj.att_stmt
109            and att_obj.att_stmt.x5c is not None
110            and len(att_obj.att_stmt.x5c) > 0
111        ):
112            # android-key attestation verifies with OpenSSL, which accepts certificates that
113            # cryptography rejects. The registration is valid, so only skip storing the certificate
114            try:
115                cert = load_der_x509_certificate(att_obj.att_stmt.x5c[0])
116            except ValueError as exc:
117                self.stage.logger.warning("failed to parse attestation certificate", exc=exc)
118            else:
119                registration_data.attest_cert = cert.public_bytes(
120                    encoding=Encoding.PEM,
121                ).decode("utf-8")
122                registration_data.attest_cert_fingerprint = fingerprint_sha256(cert)
123
124        if WebAuthnDevice.objects.filter(
125            credential_id=bytes_to_base64url(registration.credential_id)
126        ).exists():
127            raise ValidationError("Credential ID already exists.")
128
129        aaguid = registration.aaguid
130        allowed_aaguids = stage.device_type_restrictions.values_list("aaguid", flat=True)
131        if allowed_aaguids.exists():
132            invalid_error = ValidationError(
133                _("Invalid device type. Contact your {brand} administrator for help.").format(
134                    brand=self.stage.request.brand.branding_title
135                )
136            )
137            # If there are any restrictions set and we didn't get an aaguid, invalid
138            if not aaguid:
139                raise invalid_error
140            # If one of the restrictions is the "special" unknown device type UUID
141            # but we do have a device type for the given aaguid, invalid
142            if (
143                UUID(UNKNOWN_DEVICE_TYPE_AAGUID) in allowed_aaguids
144                and not WebAuthnDeviceType.objects.filter(aaguid=aaguid).exists()
145            ):
146                return registration_data
147            # Otherwise just check if the given aaguid is in the allowed aaguids
148            if UUID(aaguid) not in allowed_aaguids:
149                raise invalid_error
150        return registration_data

Validate webauthn challenge response

class AuthenticatorWebAuthnStageView(authentik.flows.stage.ChallengeStageView):
153class AuthenticatorWebAuthnStageView(ChallengeStageView):
154    """WebAuthn stage"""
155
156    response_class = AuthenticatorWebAuthnChallengeResponse
157
158    def get_challenge(self, *args, **kwargs) -> Challenge:
159        stage: AuthenticatorWebAuthnStage = self.executor.current_stage
160        self.executor.plan.context.setdefault(PLAN_CONTEXT_WEBAUTHN_ATTEMPT, 0)
161        # clear flow variables prior to starting a new registration
162        self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
163        user = self.get_pending_user()
164
165        # library accepts none so we store null in the database, but if there is a value
166        # set, cast it to string to ensure it's not a django class
167        authenticator_attachment = stage.authenticator_attachment
168        if authenticator_attachment:
169            authenticator_attachment = AuthenticatorAttachment(str(authenticator_attachment))
170
171        hints = [PublicKeyCredentialHint(h) for h in stage.hints] or None
172
173        # For compatibility with older user agents that don't support hints,
174        # auto-infer authenticatorAttachment from hints when not explicitly set.
175        # https://w3c.github.io/webauthn/#enum-hints
176        if hints and not authenticator_attachment:
177            hint_values = set(stage.hints)
178            cross_platform = {"security-key", "hybrid"}
179            platform = {"client-device"}
180            if hint_values <= cross_platform:
181                authenticator_attachment = AuthenticatorAttachment.CROSS_PLATFORM
182            elif hint_values <= platform:
183                authenticator_attachment = AuthenticatorAttachment.PLATFORM
184
185        rp_id = get_rp_id(self.request)
186
187        # Let the authenticator itself refuse to register a credential it already holds for this
188        # user. Only confirmed devices count; an unconfirmed one is not usable and must not block
189        # re-enrolling the same authenticator.
190        exclude_credentials = [
191            PublicKeyCredentialDescriptor(id=base64url_to_bytes(credential_id))
192            for credential_id in WebAuthnDevice.objects.filter(
193                user=user, rp_id=rp_id, confirmed=True
194            )
195            .order_by("pk")
196            .values_list("credential_id", flat=True)
197        ]
198
199        registration_options: PublicKeyCredentialCreationOptions = generate_registration_options(
200            rp_id=rp_id,
201            rp_name=self.request.brand.branding_title,
202            user_id=user.uid.encode("utf-8"),
203            user_name=user.username,
204            user_display_name=user.name,
205            authenticator_selection=AuthenticatorSelectionCriteria(
206                resident_key=ResidentKeyRequirement(str(stage.resident_key_requirement)),
207                user_verification=UserVerificationRequirement(str(stage.user_verification)),
208                authenticator_attachment=authenticator_attachment,
209            ),
210            attestation=AttestationConveyancePreference.DIRECT,
211            exclude_credentials=exclude_credentials,
212            hints=hints,
213            supported_pub_key_algs=supported_pub_key_algs(),
214        )
215
216        self.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = registration_options.challenge
217        return AuthenticatorWebAuthnChallenge(
218            data={
219                "registration": options_to_json_dict(registration_options),
220            }
221        )
222
223    def get_response_instance(self, data: QueryDict) -> AuthenticatorWebAuthnChallengeResponse:
224        response: AuthenticatorWebAuthnChallengeResponse = super().get_response_instance(data)
225        response.request = self.request
226        response.user = self.get_pending_user()
227        return response
228
229    def challenge_invalid(self, response):
230        stage: AuthenticatorWebAuthnStage = self.executor.current_stage
231        self.executor.plan.context.setdefault(PLAN_CONTEXT_WEBAUTHN_ATTEMPT, 0)
232        self.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_ATTEMPT] += 1
233        if (
234            stage.max_attempts > 0
235            and self.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_ATTEMPT] >= stage.max_attempts
236        ):
237            return self.executor.stage_invalid(
238                _("Exceeded maximum attempts. Contact your {brand} administrator for help.").format(
239                    brand=self.request.brand.branding_title
240                )
241            )
242        return super().challenge_invalid(response)
243
244    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
245        # Webauthn Challenge has already been validated
246        webauthn_credential: VerifiedRegistrationData = response.validated_data["response"]
247        name = "WebAuthn Device"
248        device_type = WebAuthnDeviceType.objects.filter(
249            aaguid=webauthn_credential.registration.aaguid
250        ).first()
251        if device_type and device_type.description:
252            name = device_type.description
253        WebAuthnDevice.objects.create(
254            name=name,
255            user=self.get_pending_user(),
256            public_key=bytes_to_base64url(webauthn_credential.registration.credential_public_key),
257            credential_id=bytes_to_base64url(webauthn_credential.registration.credential_id),
258            sign_count=webauthn_credential.registration.sign_count,
259            rp_id=get_rp_id(self.request),
260            device_type=device_type,
261            aaguid=webauthn_credential.registration.aaguid,
262            attestation_certificate_pem=webauthn_credential.attest_cert,
263            attestation_certificate_fingerprint=webauthn_credential.attest_cert_fingerprint,
264        )
265        # The registration challenge has been answered. Remove it, as the authenticator validation
266        # stage uses the same key and keeps a pending challenge until it's answered
267        self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
268        return self.executor.stage_ok()

WebAuthn stage

response_class = <class 'AuthenticatorWebAuthnChallengeResponse'>
def get_challenge(self, *args, **kwargs) -> authentik.flows.challenge.Challenge:
158    def get_challenge(self, *args, **kwargs) -> Challenge:
159        stage: AuthenticatorWebAuthnStage = self.executor.current_stage
160        self.executor.plan.context.setdefault(PLAN_CONTEXT_WEBAUTHN_ATTEMPT, 0)
161        # clear flow variables prior to starting a new registration
162        self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
163        user = self.get_pending_user()
164
165        # library accepts none so we store null in the database, but if there is a value
166        # set, cast it to string to ensure it's not a django class
167        authenticator_attachment = stage.authenticator_attachment
168        if authenticator_attachment:
169            authenticator_attachment = AuthenticatorAttachment(str(authenticator_attachment))
170
171        hints = [PublicKeyCredentialHint(h) for h in stage.hints] or None
172
173        # For compatibility with older user agents that don't support hints,
174        # auto-infer authenticatorAttachment from hints when not explicitly set.
175        # https://w3c.github.io/webauthn/#enum-hints
176        if hints and not authenticator_attachment:
177            hint_values = set(stage.hints)
178            cross_platform = {"security-key", "hybrid"}
179            platform = {"client-device"}
180            if hint_values <= cross_platform:
181                authenticator_attachment = AuthenticatorAttachment.CROSS_PLATFORM
182            elif hint_values <= platform:
183                authenticator_attachment = AuthenticatorAttachment.PLATFORM
184
185        rp_id = get_rp_id(self.request)
186
187        # Let the authenticator itself refuse to register a credential it already holds for this
188        # user. Only confirmed devices count; an unconfirmed one is not usable and must not block
189        # re-enrolling the same authenticator.
190        exclude_credentials = [
191            PublicKeyCredentialDescriptor(id=base64url_to_bytes(credential_id))
192            for credential_id in WebAuthnDevice.objects.filter(
193                user=user, rp_id=rp_id, confirmed=True
194            )
195            .order_by("pk")
196            .values_list("credential_id", flat=True)
197        ]
198
199        registration_options: PublicKeyCredentialCreationOptions = generate_registration_options(
200            rp_id=rp_id,
201            rp_name=self.request.brand.branding_title,
202            user_id=user.uid.encode("utf-8"),
203            user_name=user.username,
204            user_display_name=user.name,
205            authenticator_selection=AuthenticatorSelectionCriteria(
206                resident_key=ResidentKeyRequirement(str(stage.resident_key_requirement)),
207                user_verification=UserVerificationRequirement(str(stage.user_verification)),
208                authenticator_attachment=authenticator_attachment,
209            ),
210            attestation=AttestationConveyancePreference.DIRECT,
211            exclude_credentials=exclude_credentials,
212            hints=hints,
213            supported_pub_key_algs=supported_pub_key_algs(),
214        )
215
216        self.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_CHALLENGE] = registration_options.challenge
217        return AuthenticatorWebAuthnChallenge(
218            data={
219                "registration": options_to_json_dict(registration_options),
220            }
221        )

Return the challenge that the client should solve

def get_response_instance( self, data: django.http.request.QueryDict) -> AuthenticatorWebAuthnChallengeResponse:
223    def get_response_instance(self, data: QueryDict) -> AuthenticatorWebAuthnChallengeResponse:
224        response: AuthenticatorWebAuthnChallengeResponse = super().get_response_instance(data)
225        response.request = self.request
226        response.user = self.get_pending_user()
227        return response

Return the response class type

def challenge_invalid(self, response):
229    def challenge_invalid(self, response):
230        stage: AuthenticatorWebAuthnStage = self.executor.current_stage
231        self.executor.plan.context.setdefault(PLAN_CONTEXT_WEBAUTHN_ATTEMPT, 0)
232        self.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_ATTEMPT] += 1
233        if (
234            stage.max_attempts > 0
235            and self.executor.plan.context[PLAN_CONTEXT_WEBAUTHN_ATTEMPT] >= stage.max_attempts
236        ):
237            return self.executor.stage_invalid(
238                _("Exceeded maximum attempts. Contact your {brand} administrator for help.").format(
239                    brand=self.request.brand.branding_title
240                )
241            )
242        return super().challenge_invalid(response)

Callback when the challenge has the incorrect format

def challenge_valid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
244    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
245        # Webauthn Challenge has already been validated
246        webauthn_credential: VerifiedRegistrationData = response.validated_data["response"]
247        name = "WebAuthn Device"
248        device_type = WebAuthnDeviceType.objects.filter(
249            aaguid=webauthn_credential.registration.aaguid
250        ).first()
251        if device_type and device_type.description:
252            name = device_type.description
253        WebAuthnDevice.objects.create(
254            name=name,
255            user=self.get_pending_user(),
256            public_key=bytes_to_base64url(webauthn_credential.registration.credential_public_key),
257            credential_id=bytes_to_base64url(webauthn_credential.registration.credential_id),
258            sign_count=webauthn_credential.registration.sign_count,
259            rp_id=get_rp_id(self.request),
260            device_type=device_type,
261            aaguid=webauthn_credential.registration.aaguid,
262            attestation_certificate_pem=webauthn_credential.attest_cert,
263            attestation_certificate_fingerprint=webauthn_credential.attest_cert_fingerprint,
264        )
265        # The registration challenge has been answered. Remove it, as the authenticator validation
266        # stage uses the same key and keeps a pending challenge until it's answered
267        self.executor.plan.context.pop(PLAN_CONTEXT_WEBAUTHN_CHALLENGE, None)
268        return self.executor.stage_ok()

Callback when the challenge has the correct format