Authentication methods inside the authorization code flow

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

The authentication methods are not OAuth grants. They are how the user proves who they are inside the authorization code flow: between the client’s GET /oauth2/authorize and the moment the server issues the code. Every method ends the same way: it adds an authentication factor (a FACTOR_* authority stamped with the time it was presented) to the session, the multi-factor policy decides whether that is enough, and the saved authorization request resumes. The client never sees which method was used, except through the amr, acr and auth_time claims of the tokens.

At a glance
  • Actors: the user and their browser, the client application (for example the bff, see Authorization code with PKCE through the BFF), the authorization server (port 9000) and, for one-time tokens, the mail server or SMS gateway.

  • Preconditions:

    • Password: always on (formLogin in SecurityConfig).

    • Passkeys: always on; the relying party is set with authserver.passkeys.rp-id, rp-name and allowed-origins. A passkey must first be registered from GET /account/passkeys by a signed-in user.

    • One-time tokens: always on for e-mail; SMS needs one of the profiles dev, test (logging sender), twilio or sns, and a verified phone on the account.

    • X.509: authserver.x509.enabled=true plus a transport (authserver.x509.forwarded-header with trusted-proxies, or authserver.x509.port), and a certificate bound through POST /api/account/certificates.

    • Second factor: required when the client has mfaRequired, an administrator set users.mfa_required, or the user has a confirmed second factor.

  • Endpoints: GET /login, POST /login (password), POST /webauthn/authenticate/options and POST /login/webauthn (passkeys), POST /ott/generate, GET /login/ott, POST /login/ott, GET /login/ott/confirm (one-time tokens), POST /login/x509 (certificate), GET /login/second-factor, POST /login/second-factor/totp, POST /login/second-factor/ott, GET /login/second-factor/recovery-codes.

Steps

  1. The client sends the browser to GET /oauth2/authorize (with PKCE). Nobody is signed in, so the protocol chain saves the request and redirects to GET /login (LoginUrlAuthenticationEntryPoint in SecurityConfig).

  2. LoginController renders templates/login.html: the password form plus every LoginMethodFragment bean (PasskeyLoginMethodFragment, OttLoginMethodFragment, SocialLoginMethodFragment when a provider is configured, X509LoginMethodFragment when X.509 is enabled).

  3. The user signs in with one primary method (sections below). The method’s filter adds its factor to the authentication, changes the session id and redirects to the saved request.

  4. GET /oauth2/authorize is evaluated again. MfaProtocolChainCustomizer (inside the authorization endpoint validator) and MfaLoginChainCustomizer (on /oauth2/consent) ask MfaAuthorizationManager, which applies MfaPolicy. When a second factor is required and missing, SecondFactorRequiredEntryPoint sends the browser to GET /login/second-factor (see Second factors).

  5. StepUpAuthorizationRequestConverter checks acr_values and max_age when the client sent them (see Step-up authentication).

  6. The consent page is shown if the client needs it, then the code is issued and the flow continues as described in Authorization code with PKCE through the BFF.

Password

The password form posts to POST /login, a Spring Security filter endpoint. UserAccountUserDetailsService loads the account and the DelegatingPasswordEncoder built by PasswordConfiguration verifies the hash: Argon2 by default, with bcrypt and PBKDF2 hashes still accepted and upgraded on the next successful sign-in (UpgradePasswordHashUseCase). Spring Security adds FACTOR_PASSWORD, which PasswordFactor registers as a PRIMARY factor with amr pwd. See Passwords and accounts.

    /**
     * Creates the password encoder: a delegating encoder whose default is Argon2, with bcrypt and PBKDF2 kept for
     * legacy hashes.
     *
     * @return the delegating password encoder.
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new DelegatingPasswordEncoder(DEFAULT_ENCODING_ID, Map.of(
                DEFAULT_ENCODING_ID, Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8(),
                BCRYPT_ENCODING_ID, new BCryptPasswordEncoder(),
                PBKDF2_ENCODING_ID, Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8()));
    }
sequenceDiagram autonumber participant B as Browser participant AS as Authorization server participant DB as Database B->>AS: GET /oauth2/authorize AS-->>B: 302 to /login (request saved) B->>AS: GET /login AS-->>B: login page with password form and fragments B->>AS: POST /login with username, password and CSRF token AS->>DB: load account (UserAccountUserDetailsService) AS->>AS: verify Argon2 hash, add FACTOR_PASSWORD AS-->>B: 302 to saved /oauth2/authorize B->>AS: GET /oauth2/authorize AS->>AS: MfaPolicy check AS-->>B: 302 to client redirect_uri with code

Passkeys (WebAuthn)

The passkey button and conditional-mediation autofill come from PasskeyLoginMethodFragment and passkeys.js. The script asks POST /webauthn/authenticate/options for a challenge, runs the browser’s WebAuthn ceremony and posts the signed assertion to POST /login/webauthn. Both endpoints belong to Spring Security’s http.webAuthn(…​), enabled by PasskeyChainCustomizer, whose shared UserDetailsService is AccountStatusUserDetailsService, so a disabled, locked or expired account is refused. PasskeyFactor registers FACTOR_WEBAUTHN as PRIMARY_STRONG (amr hwk): a passkey alone satisfies MfaPolicy, so no second factor is asked. See Passkeys (WebAuthn).

    /**
     * Declares the passkey factor.
     *
     * @return the factor.
     */
    @Bean
    public AuthenticationFactor passkeyAuthenticationFactor() {
        return new AuthenticationFactor(ID, AMR_VALUE, AUTHORITY, FactorStrength.PRIMARY_STRONG);
    }
sequenceDiagram autonumber participant B as Browser participant A as Authenticator participant AS as Authorization server B->>AS: GET /oauth2/authorize AS-->>B: 302 to /login B->>AS: POST /webauthn/authenticate/options AS-->>B: challenge and allowed credentials B->>A: navigator.credentials.get with the challenge A-->>B: assertion signed by the passkey B->>AS: POST /login/webauthn with the assertion AS->>AS: verify signature, add FACTOR_WEBAUTHN (PRIMARY_STRONG) AS-->>B: redirect to saved /oauth2/authorize B->>AS: GET /oauth2/authorize AS-->>B: 302 to client redirect_uri with code

E-mail or SMS code and magic link

The form of OttLoginMethodFragment posts the user name, a channel (email or sms) and a kind (code or link) to POST /ott/generate, Spring Security’s oneTimeTokenLogin(…​) endpoint enabled by OttChainCustomizer. OttRateLimitFilter runs first and answers 429 when the per-address or per-identifier limit is reached. The answer is always the same redirect to GET /login/ott, whether or not the account exists, so nothing reveals accounts. The code is bound to the session (PendingOtt) and delivered after the transaction commits by OttDeliveryListener.

  • A code is typed on the GET /login/ott page and posted to POST /login/ott, verified by OttCodeAuthenticationProvider through VerifyOneTimeCodeUseCase.

  • A magic link (e-mail only) opens GET /login/ott/confirm, whose button posts the token to POST /login/ott (OttLinkAuthenticationProvider). A GET never spends the token, so a mail scanner that opens the link cannot use it.

The e-mail code or link adds FACTOR_OTT (amr otp), the SMS code adds FACTOR_OTT_SMS (amr sms); both are PRIMARY, so a user who requires MFA is then asked for a second factor. See One-time tokens (e-mail, magic links and SMS).

/**
 * Registers the one-time token methods as authentication factors. One authority cannot carry two strengths and the
 * registry refuses two factors with the same authority, so each use of each channel is a factor of its own: the
 * e-mail code or magic link as a sign-in ({@code FACTOR_OTT}, Spring Security's own constant) and the SMS code as a
 * sign-in are {@link FactorStrength#PRIMARY} (they prove the possession of a mailbox or a phone, which is as strong as
 * a password and no more), and the same two as the second factor of a user who already signed in with a primary
 * factor are {@link FactorStrength#SECOND}. The {@code amr} values are those of RFC 8176: {@code otp} for the code or
 * the link sent by e-mail and {@code sms} for the code sent by SMS.
 */
@Configuration(proxyBeanMethods = false)
public class OttFactors {

    /** RFC 8176 {@code amr} value of a one-time password sent by e-mail. */
    public static final String EMAIL_AMR_VALUE = "otp";

    /** RFC 8176 {@code amr} value of a one-time password sent by SMS. */
    public static final String SMS_AMR_VALUE = "sms";

    /** Authority of the e-mail code or magic link as a sign-in. */
    public static final String EMAIL_AUTHORITY = FactorGrantedAuthority.OTT_AUTHORITY;

    /** Authority of the SMS code as a sign-in. */
    public static final String SMS_AUTHORITY = "FACTOR_OTT_SMS";

    /** Authority of the e-mail code or magic link as a second factor. */
    public static final String EMAIL_SECOND_FACTOR_AUTHORITY = "FACTOR_OTT_EMAIL_2FA";

    /** Authority of the SMS code as a second factor. */
    public static final String SMS_SECOND_FACTOR_AUTHORITY = "FACTOR_OTT_SMS_2FA";

    /**
     * Declares the e-mail code and magic link as a sign-in.
     *
     * @return the factor.
     */
    @Bean
    public AuthenticationFactor ottEmailAuthenticationFactor() {
        return new AuthenticationFactor("ott-email", EMAIL_AMR_VALUE, EMAIL_AUTHORITY, FactorStrength.PRIMARY);
    }

    /**
     * Declares the SMS code as a sign-in.
     *
     * @return the factor.
     */
    @Bean
    public AuthenticationFactor ottSmsAuthenticationFactor() {
        return new AuthenticationFactor("ott-sms", SMS_AMR_VALUE, SMS_AUTHORITY, FactorStrength.PRIMARY);
    }

    /**
     * Declares the e-mail code and magic link as a second factor.
     *
     * @return the factor.
     */
    @Bean
    public AuthenticationFactor ottEmailSecondAuthenticationFactor() {
        return new AuthenticationFactor("ott-email-2fa", EMAIL_AMR_VALUE, EMAIL_SECOND_FACTOR_AUTHORITY,
                FactorStrength.SECOND);
    }

    /**
     * Declares the SMS code as a second factor.
     *
     * @return the factor.
     */
    @Bean
    public AuthenticationFactor ottSmsSecondAuthenticationFactor() {
        return new AuthenticationFactor("ott-sms-2fa", SMS_AMR_VALUE, SMS_SECOND_FACTOR_AUTHORITY,
                FactorStrength.SECOND);
    }
sequenceDiagram autonumber participant B as Browser participant AS as Authorization server participant M as Mail server or SMS gateway B->>AS: GET /oauth2/authorize AS-->>B: 302 to /login B->>AS: POST /ott/generate with username, channel and kind AS-->>B: 302 to /login/ott (same answer for unknown accounts) AS-)M: after commit, send code or magic link M-)B: code or link reaches the user alt code B->>AS: POST /login/ott with the code else magic link B->>AS: GET /login/ott/confirm with the token AS-->>B: confirmation page with a button B->>AS: POST /login/ott with the token end AS->>AS: verify, add FACTOR_OTT or FACTOR_OTT_SMS AS-->>B: redirect to saved /oauth2/authorize

X.509 client certificate

X509LoginMethodFragment renders a button whose form posts, with the CSRF token, to POST /login/x509. The CSRF filter runs before the X.509 filter, so a page of another site cannot sign a browser in with its certificate, and a GET of that path signs nobody in. The certificate arrives either through the dedicated TLS port (X509TlsConnectorCustomizer) or in a header set by a reverse proxy, which ForwardedCertificateFilter reads only for a request from trusted-proxies. CertificatePrincipalExtractor turns it into its SHA-256 fingerprint (an expired or not yet valid certificate yields an unreadable one), X509UserDetailsService maps the fingerprint to an account through ResolveCertificateLoginUseCase, and X509AuthenticationSuccessHandler grants FACTOR_X509 (PRIMARY_STRONG, amr sc or hwk from authserver.x509.amr) and changes the session id. See X.509 client certificates.

    /**
     * Declares the certificate factor.
     *
     * @param properties settings of the sign-in with a certificate, which choose the reported {@code amr} value.
     * @return the factor.
     */
    @Bean
    public AuthenticationFactor x509AuthenticationFactor(final X509Properties properties) {
        return new AuthenticationFactor(ID, properties.amr(), AUTHORITY, FactorStrength.PRIMARY_STRONG);
    }
sequenceDiagram autonumber participant B as Browser participant P as Reverse proxy or TLS port participant AS as Authorization server participant DB as Database B->>AS: GET /oauth2/authorize AS-->>B: 302 to /login B->>P: POST /login/x509 with CSRF token and client certificate P->>AS: request with the certificate AS->>AS: CSRF check, then fingerprint (CertificatePrincipalExtractor) AS->>DB: find bound account (ResolveCertificateLoginUseCase) AS->>AS: add FACTOR_X509 (PRIMARY_STRONG), new session id AS-->>B: redirect to saved /oauth2/authorize

Second factors

When the policy is not satisfied, the browser lands on GET /login/second-factor (SecondFactorController, page templates/second-factor.html), which shows every SecondFactorFragment that applies to the user:

  • TOTP (TotpSecondFactorFragment): the code of an authenticator app, or a recovery code, posted to POST /login/second-factor/totp and verified by TotpAuthenticationProvider. It adds FACTOR_TOTP (SECOND, amr otp). A user without a confirmed app sees the enrolment form instead; ConfirmTotpAtSignInUseCase confirms it and GET /login/second-factor/recovery-codes shows the recovery codes once.

  • One-time token (OttSecondFactorFragment): an e-mail code or link, or an SMS code, posted to POST /login/second-factor/ott (OttSecondFactorFilter). It adds FACTOR_OTT_EMAIL_2FA (amr otp) or FACTOR_OTT_SMS_2FA (amr sms). OttSecondFactorChannels allows neither the channel that signed the user in, nor SMS without a verified phone, nor e-mail while the user has another confirmed second factor.

  • Passkey (PasskeySecondFactorFragment): the same WebAuthn ceremony posted to POST /login/webauthn. Spring merges FACTOR_WEBAUTHN with FACTOR_PASSWORD, so amr becomes pwd, hwk, mfa.

  • Trusted device (TrustedDeviceFilter): on GET /login/second-factor only, a valid signed __Host-TRUSTED-DEVICE cookie grants FACTOR_TRUSTED_DEVICE (REMEMBERED) and resumes the request without a form. It satisfies the sign-in policy but is never reported in amr and never satisfies a step-up.

Every verification starts with CheckSecondFactorLockoutUseCase and counts failures through RegisterSecondFactorFailureUseCase, so all factors share one lockout (authserver.mfa.max-failed-attempts, authserver.mfa.lockout). On success the filter changes the session id, renews the CSRF token and redirects to the saved authorization request. See Multi-factor authentication and step-up.

flowchart TD A["GET /oauth2/authorize after a primary factor"] --> B{"MFA required? (client mfaRequired, users.mfa_required or a confirmed second factor)"} B -- no --> OK["Continue: consent, then code"] B -- yes --> C{"MfaPolicy satisfied?"} C -- "PRIMARY_STRONG factor (passkey, X.509, trusted federated)" --> OK C -- "PRIMARY plus SECOND or REMEMBERED" --> OK C -- "PRIMARY only" --> D["302 to /login/second-factor (request saved)"] D --> E{"Trusted device cookie valid?"} E -- yes --> F["Grant FACTOR_TRUSTED_DEVICE"] E -- no --> G["Show fragments: TOTP, one-time token, passkey"] G --> H{"Code or assertion valid and not locked out?"} H -- no --> I["Count failure, show the page with an error"] I --> G H -- yes --> J["Grant the SECOND factor, new session id"] F --> K["Resume saved /oauth2/authorize"] J --> K K --> OK

Tokens and claims

MfaClaimsContributor (a JwtClaimsContributor) writes the claims from the factors the session holds, read through FactorTimeline:

  • amr: the amr value of each reported factor in the order presented, each once, plus mfa when the session is multi-factor (MfaPolicy.isMultiFactor: two distinct reported factors, or one factor that is multi-factor alone). pwd (password), hwk (passkey), otp (e-mail code or link, TOTP), sms (SMS code), sc or hwk (X.509), fed (social login, see Social login and identity brokering). The trusted device is never reported.

  • acr: urn:irurueta:acr:mfa when the session is multi-factor (same rule), otherwise urn:irurueta:acr:pwd. A passkey or a certificate alone is a strong factor but proves one thing, so it is reported with the password class; only a trusted provider’s multi-factor sign-in (FACTOR_FEDERATED_MFA) is multi-factor alone.

  • auth_time: on access tokens, the time the earliest primary factor was presented (the framework sets it on ID tokens), so a later second factor never makes a sign-in look newer.

/**
 * Adds to the access and ID tokens how the user authenticated: {@code amr} (the RFC 8176 values of the factors really
 * presented, plus {@code mfa} when there are at least two), {@code acr} (the class of the authentication, see
 * {@link AuthenticationContextClass}) and {@code auth_time} (the epoch second the primary factor was presented, a
 * number per OIDC; access tokens only, because the framework sets it on ID tokens). Every value comes from the
 * {@link FactorTimeline}, which reads the {@link org.springframework.security.core.authority.FactorGrantedAuthority}
 * instances of the principal: authorities of an unknown factor and of a remembered (trusted) device are ignored, so a
 * browser that skipped the second factor gets {@code amr [pwd]} and the password class. A token with no counted factor
 * (for example of the client credentials grant) gets none of the claims.
 */
@Component
@Order(MfaClaimsContributor.ORDER)
@RequiredArgsConstructor
public class MfaClaimsContributor implements JwtClaimsContributor {

    /** Order of the contributor: after the built-in claims and the default contributors. */
    public static final int ORDER = 100;

    /** RFC 8176 {@code amr} value that tells that more than one factor was used. */
    public static final String MULTI_FACTOR_AMR_VALUE = "mfa";

    /** Reads the counted factors of the principal and their instants. */
    private final FactorTimeline factorTimeline;

    @Override
    public void contribute(final OAuth2TokenContext context, final Map<String, Object> claims) {
        final var principal = context.getPrincipal();
        if (principal == null) {
            return;
        }
        final var authTime = factorTimeline.authTime(principal);
        if (authTime.isEmpty()) {
            return;
        }
        // a mutable list on purpose: the authorization store only deserializes allow-listed types
        final var amr = new ArrayList<String>(factorTimeline.amrValues(principal));
        final var multiFactor = factorTimeline.isMultiFactor(principal);
        if (multiFactor) {
            amr.add(MULTI_FACTOR_AMR_VALUE);
        }
        claims.put(IdTokenClaimNames.AMR, amr);
        claims.put(IdTokenClaimNames.ACR,
                multiFactor ? AuthenticationContextClass.MULTI_FACTOR : AuthenticationContextClass.PASSWORD);
        // the framework sets auth_time itself on ID tokens (as a date it expects to read back on refresh)
        if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
            claims.put(IdTokenClaimNames.AUTH_TIME, authTime.get().getEpochSecond());
        }
    }
}

How it is tested

  • Password: PasswordAuthenticationIT, PasswordUpgradeIT and AuthorizationCodePkceIT in auth-server/boot; SignInSmokeIT and BffEndToEndIT in e2e-tests (packaged jars and headless Chromium).

  • Passkeys: PasskeyPagesIT and PasskeyRegistrationIT in auth-server/boot; PasskeyEndToEndIT in e2e-tests (virtual authenticator, passkey alone and password plus passkey).

  • One-time tokens: OttEmailCodeIT, OttMagicLinkIT, OttSmsIT, OttEnumerationIT, OttRateLimitIT and OttPagesIT in auth-server/boot; OttEndToEndIT in e2e-tests.

  • X.509: X509LoginIT and X509TlsLoginIT in auth-server/boot.

  • Second factors: TotpLoginIT, MfaPasswordOnlyForcedIT, RecoveryCodeIT, TrustedDeviceIT and SecondFactorLockoutIT in auth-server/boot.