Passkeys (WebAuthn)

This documentation was generated with the assistance of AI. Please report any inaccuracies.

A passkey is a phishing-resistant credential held by the user’s device. It works as a passwordless primary sign-in and as the second factor after a password. The ceremonies are Spring Security’s own (http.webAuthn(…​)); this server adds the factor registration, the persistence port, the account API and the pages.

Factor and sign-in

PasskeyFactor registers FACTOR_WEBAUTHN as a strong primary factor (amr value hwk), so a passkey alone satisfies MfaPolicy. After a password, the factors merge and amr is pwd, hwk and mfa; see Multi-factor authentication and step-up.

    /**
     * Declares the passkey factor.
     *
     * @return the factor.
     */
    @Bean
    public AuthenticationFactor passkeyAuthenticationFactor() {
        return new AuthenticationFactor(ID, AMR_VALUE, AUTHORITY, FactorStrength.PRIMARY_STRONG);
    }

The chain customizer applies the relying party settings, guards the registration endpoints, denies DELETE /webauthn/register/** (a passkey is removed only through the account API, with step-up) and gives the WebAuthn filter the chain’s session strategy and a user service that refuses disabled accounts.

    @Override
    public void customize(final HttpSecurity http) {
        http.setSharedObject(UserDetailsService.class, new AccountStatusUserDetailsService(userDetailsService));
        http.authorizeHttpRequests(authorize -> authorize
                .requestMatchers(SCRIPT_PATH, AUTHENTICATION_OPTIONS_PATH, AUTHENTICATION_PATH).permitAll()
                .requestMatchers(HttpMethod.DELETE, PasskeyRegistrationAuthorizationManager.REGISTRATION_PATH + "/**")
                .denyAll()
                .requestMatchers(PasskeysPageController.PASSKEYS_PATH).access(mfaAuthorizationManager));
        http.addFilterBefore(
                new PasskeyRegistrationFilter(new PasskeyRegistrationAuthorizationManager(mfaAuthorizationManager)),
                AuthorizationFilter.class);
        http.addFilterBefore(
                new PasskeySecondFactorLockoutFilter(secondFactorUserResolver, checkSecondFactorLockoutUseCase),
                BasicAuthenticationFilter.class);
        http.webAuthn(webAuthn -> webAuthn
                .rpName(properties.rpName())
                .rpId(properties.rpId())
                .allowedOrigins(new LinkedHashSet<>(properties.allowedOrigins()))
                .disableDefaultRegistrationPage(true)
                .addObjectPostProcessor(new SessionStrategyPostProcessor(http)));
    }
    /**
     * Declares the customizer that enables {@code http.webAuthn(...)}, permits its public endpoints, keeps the
     * registration endpoints behind the multi-factor policy and removes the ones that would bypass the step-up. It is
     * applied after the TOTP customizer.
     *
     * @param properties           relying party settings.
     * @param authorizationManager applies the multi-factor policy.
     * @param userDetailsService   loads the account of the user a passkey belongs to.
     * @param userResolver         resolves the account of the signed-in user, for the lockout check.
     * @param lockoutUseCase       tells whether the second factor of a user is locked.
     * @return the customizer.
     */
    @Bean
    @Order(PasskeyChainCustomizer.ORDER)
    public LoginChainCustomizer passkeyChainCustomizer(final PasskeyProperties properties,
            final MfaAuthorizationManager authorizationManager, final UserDetailsService userDetailsService,
            final SecondFactorUserResolver userResolver, final CheckSecondFactorLockoutUseCase lockoutUseCase) {
        return new PasskeyChainCustomizer(properties, authorizationManager, userDetailsService, userResolver,
                lockoutUseCase);
    }

The login page shows a passkey button and conditional-mediation autofill; the second-factor page offers "use a passkey".

<div th:fragment="login" class="passkey-login" data-passkey-login
     th:attr="data-csrf-header=${_csrf?.headerName},data-csrf-token=${_csrf?.token}"
     th:data-options-url="@{/webauthn/authenticate/options}" th:data-login-url="@{/login/webauthn}"
     th:data-error-url="@{/login?error}" th:data-failure-message="#{passkeys.login.failed}">
  <h2 th:text="#{passkeys.login.heading}">Sign in with a passkey</h2>
  <p>
    <label for="passkey-username" th:text="#{passkeys.login.username}">Username</label>
    <input type="text" id="passkey-username" name="passkey-username" autocomplete="username webauthn"
           data-passkey-field>
  </p>
  <button type="button" data-passkey-button th:text="#{passkeys.login.button}">Use a passkey</button>
  <p role="alert" data-passkey-error hidden></p>
  <script th:src="@{/js/passkeys.js}" defer></script>
</div>
<div th:fragment="form" th:if="${passkeysAvailable}" class="passkey-second-factor" data-passkey-login
     th:attr="data-csrf-header=${_csrf?.headerName},data-csrf-token=${_csrf?.token}"
     th:data-options-url="@{/webauthn/authenticate/options}" th:data-login-url="@{/login/webauthn}"
     th:data-error-url="@{/login/second-factor?error}" th:data-failure-message="#{passkeys.login.failed}">
  <h2 th:text="#{passkeys.second.heading}">Use a passkey</h2>
  <p th:text="#{passkeys.second.instructions}">Confirm with a passkey registered to your account.</p>
  <button type="button" data-passkey-button th:text="#{passkeys.second.button}">Use a passkey</button>
  <p role="alert" data-passkey-error hidden></p>
  <script th:src="@{/js/passkeys.js}" defer></script>
</div>

Registration and management

A passkey is registered from GET /account/passkeys, which needs a signed-in session, and managed with GET, PATCH and DELETE /api/account/passkeys (the id is the base64url credential id). Deleting one calls StepUpGuard while the account has a confirmed second factor.

  <section class="passkey-register" data-passkey-register
           th:attr="data-csrf-header=${_csrf?.headerName},data-csrf-token=${_csrf?.token}"
           th:data-options-url="@{/webauthn/register/options}" th:data-register-url="@{/webauthn/register}"
           th:data-label-message="#{passkeys.account.labelRequired}"
           th:data-success-message="#{passkeys.account.registered}"
           th:data-failure-message="#{passkeys.account.failed}">
    <h2 th:text="#{passkeys.account.add}">Add a passkey</h2>
    <p>
      <label for="passkey-label" th:text="#{passkeys.account.label}">Name of the passkey</label>
      <input type="text" id="passkey-label" name="passkey-label" required maxlength="100" autocomplete="off"
             data-passkey-label>
    </p>
    <button type="button" data-passkey-register-button th:text="#{passkeys.account.register}">Register</button>
    <p role="status" data-passkey-status hidden></p>
    <p role="alert" data-passkey-error hidden></p>
    <script th:src="@{/js/passkeys.js}" defer></script>
  </section>
    Passkey:
      type: object
      description: A WebAuthn credential registered by the account
      required: [ id, label, createdAt, signatureCount, backupEligible, backedUp ]
      properties:
        id:
          type: string
          minLength: 1
          maxLength: 1000
          pattern: '^[A-Za-z0-9_-]+$'
          description: Credential identifier, as unpadded base64url.
        label:
          type: string
          minLength: 1
          maxLength: 100
          description: Name that identifies the passkey in the list.
        createdAt:
          type: string
          format: date-time
          description: When the passkey was registered.
        lastUsedAt:
          type: [ string, 'null' ]
          format: date-time
          description: When the passkey was last used to authenticate; equal to createdAt until its first use, because the credential store always records a value.
        signatureCount:
          type: integer
          format: int64
          minimum: 0
          description: Signature counter reported by the authenticator at its last use.
        backupEligible:
          type: boolean
          description: Whether the credential may be synchronised (the WebAuthn BE flag).
        backedUp:
          type: boolean
          description: Whether the credential is currently synchronised (the WebAuthn BS flag).
    RenamePasskeyRequest:
      type: object
      description: The new label of a passkey
      required: [ label ]
      properties:
        label:
          type: string
          description: New name of the passkey; it must contain a non-blank character.
          minLength: 1
          maxLength: 100
          pattern: '[\s\S]*\S[\s\S]*'

Settings

  passkeys:
    # Relying party of the passkeys (WebAuthn). The id is the host name credentials are scoped to and the origins are
    # the ones browsers may run the ceremonies from: both default to the local development values and must be set to
    # the public host name of a real deployment.
    rp-name: ${AUTHSERVER_PASSKEYS_RP_NAME:Irurueta Auth Server}
    rp-id: ${AUTHSERVER_PASSKEYS_RP_ID:localhost}
    allowed-origins: ${AUTHSERVER_PASSKEYS_ALLOWED_ORIGINS:http://localhost:9000}
/**
 * Relying party settings of the passkeys (WebAuthn), bound once from {@code authserver.passkeys.*} and injected
 * wherever one of them is needed. An invalid value stops the application at startup. A browser only accepts a
 * credential whose relying party id is the host of the page (or a registrable suffix of it) and whose origin is one of
 * the allowed ones, so a deployment must set {@code rp-id} and {@code allowed-origins} to its public host name; the
 * shipped {@code application.yml} defaults to {@code localhost} for local runs only.
 *
 * @param rpName         name of the relying party shown by the authenticator (default {@code Irurueta Auth Server}).
 * @param rpId           relying party id: the host name credentials are scoped to.
 * @param allowedOrigins origins (scheme, host and port) the browser may run the WebAuthn ceremonies from.
 */
@ConfigurationProperties("authserver.passkeys")
public record PasskeyProperties(
        @DefaultValue("Irurueta Auth Server") String rpName,
        String rpId,
        List<String> allowedOrigins) {

    /**
     * Validates the settings and copies the origins.
     *
     * @throws IllegalArgumentException if the name or the id is blank, or there is no allowed origin or one is blank.
     */
    public PasskeyProperties {
        if (rpName == null || rpName.isBlank()) {
            throw new IllegalArgumentException("authserver.passkeys.rp-name must not be blank");
        }
        if (rpId == null || rpId.isBlank()) {
            throw new IllegalArgumentException("authserver.passkeys.rp-id must not be blank");
        }
        if (allowedOrigins == null || allowedOrigins.isEmpty()
                || allowedOrigins.stream().anyMatch(origin -> origin == null || origin.isBlank())) {
            throw new IllegalArgumentException(
                    "authserver.passkeys.allowed-origins must list at least one origin and none may be blank");
        }
        allowedOrigins = List.copyOf(allowedOrigins);
    }
}

Database

Migration V500 (issue #5); see Data model.

CREATE TABLE user_entities
(
    id           varchar(1000) NOT NULL,
    name         varchar(100)  NOT NULL,
    display_name varchar(200),
    PRIMARY KEY (id),
    CONSTRAINT uq_user_entities_name UNIQUE (name)
);

CREATE TABLE user_credentials
(
    credential_id                varchar(1000) NOT NULL,
    user_entity_user_id          varchar(1000) NOT NULL,
    public_key                   bytea         NOT NULL,
    signature_count              bigint,
    uv_initialized               boolean,
    backup_eligible              boolean       NOT NULL,
    authenticator_transports     varchar(1000),
    public_key_credential_type   varchar(100),
    backup_state                 boolean       NOT NULL,
    attestation_object           bytea,
    attestation_client_data_json bytea,
    created                      timestamp with time zone,
    last_used                    timestamp with time zone,
    label                        varchar(1000) NOT NULL,
    PRIMARY KEY (credential_id)
);

CREATE INDEX ix_user_credentials_user_entity_user_id ON user_credentials (user_entity_user_id);

Limitations

  • Passkey-first sign-up is not possible: registration needs an authenticated session, so an account starts with another primary factor.

  • A passkey-only session gets the password acr, by design: the passkey is a strong factor but not multi-factor alone (user verification is only preferred), so it cannot satisfy a step-up and the user adds a second factor (see Multi-factor authentication and step-up).

  • Spring’s relying party operations fix user verification to preferred.

  • lastUsedAt equals createdAt until the first use, because Spring’s schema requires last_used.