Step-up authentication
| This documentation was generated with the assistance of AI. Please report any inaccuracies. |
Step-up authentication lets a client or an API demand a stronger or more recent sign-in than the one the user already
has. A client asks for it up front with the OpenID Connect acr_values and max_age parameters of
GET /oauth2/authorize; the authorization server then either continues, sends the user to the second-factor page or
makes them sign in again. An API asks for it after the fact, per RFC 9470: it answers 401 with
WWW-Authenticate: Bearer error="insufficient_user_authentication" and the acr_values and max_age it needs, and
the client sends the user through the authorization server again with those values and retries with the new token.
This repository has two such APIs: the authorization server’s own account API (StepUpGuard) and the resource
server’s document deletion (StepUpAuthorizationManager).
-
Actors: the user and their browser, the client (for example the
bff), the authorization server, and the API that demands the step-up (the authorization server’s/api/account/**or the resource server on port 8081). -
Preconditions:
-
Authorization request: nothing to enable;
StepUpProtocolChainCustomizeris always on. Only the classesurn:irurueta:acr:pwdandurn:irurueta:acr:mfaare understood; other values are ignored. -
Account API: the account has a confirmed second factor (otherwise
StepUpGuardlets the call through, since the user could not step up); the age limit isauthserver.mfa.step-up-max-age(defaultPT5M). -
Resource server:
resourceserver.step-up.enabled(defaulttrue),acr-values(defaulturn:irurueta:acr:mfa) andmax-age(defaultPT5M), bound intoStepUpProperties; the token must have thedocuments.deletescope.
-
-
Endpoints:
GET /oauth2/authorizewithacr_valuesandmax_age,GET /login,GET /login/second-factor; on the account APIDELETE /api/account/totp,POST /api/account/recovery-codes,DELETE /api/account/trusted-devices/{id},DELETE /api/account/passkeys/{id},PUTandDELETE /api/account/phone,POST /api/account/certificates,DELETE /api/account/certificates/{id},DELETE /api/account/identities/{id}; on the resource serverDELETE /api/documents/{id}.
Steps
Step-up on the authorization request
-
The client sends
GET /oauth2/authorizewithacr_values=urn:irurueta:acr:mfaand, optionally,max_agein seconds. -
If nobody is signed in, the user signs in first (see Authentication methods inside the authorization code flow).
-
StepUpProtocolChainCustomizerinstalledStepUpAuthorizationRequestConverterfirst among the authorization endpoint converters. It reads the session’s factors throughFactorTimeline:-
If more than
max_ageseconds have passed since the primary factor was presented (auth_time), it throwsReauthenticationRequiredException.SecondFactorErrorResponseHandlerhands it toReauthenticationEntryPoint, which clears the security context, saves the request and redirects toGET /login. -
Otherwise, if
acr_valuesnames the multi-factor class only and the session is not multi-factor (MfaPolicy.isMultiFactor: two distinct reported factors, or one factor that is multi-factor alone, today only a trusted provider’sFACTOR_FEDERATED_MFA), it throwsSecondFactorRequiredException.forStepUp(), andSecondFactorRequiredEntryPointredirects toGET /login/second-factor. In this case the page renders the second-factor forms even on a trusted device, because a remembered device never satisfies a step-up. -
Otherwise the request continues. A request that also lists
urn:irurueta:acr:pwdis satisfied by the password.
-
-
After the new sign-in or second factor, the saved request resumes and the code is issued. The tokens carry the new
acrandauth_time.
Step-up demanded by an API (RFC 9470)
-
The client calls a sensitive operation with a bearer token whose
acrisurn:irurueta:acr:pwd, or whoseauth_timeis too old. -
On the authorization server, the controller (
TotpController,RecoveryCodeController,TrustedDeviceController,PasskeyController,PhoneController,CertificateController,IdentityController) first callsStepUpGuard.requireRecentMultiFactor. While the account has a confirmed second factor (HasConfirmedSecondFactorUseCase), the JWT’sacrmust beurn:irurueta:acr:mfaand itsauth_timewithinauthserver.mfa.step-up-max-age; otherwise it throwsInsufficientUserAuthenticationExceptionandMfaExceptionHandleranswers401with the challenge and a problem body. -
On the resource server,
StepUpAuthorizationManagerguardsDELETE /api/documents/{id}: with theSCOPE_documents.deleteauthority but without an acceptedacrand a recent enoughauth_time, it returns aStepUpRequiredDecision, andStepUpAccessDeniedHandleranswers401with the challenge. Other denials keep the RFC 6750 answers (403for a missing scope). -
The client reads
acr_valuesandmax_agefromWWW-Authenticate, sends the user toGET /oauth2/authorizewith them, and exchanges the new code for a token. -
The client retries the call with the new token, which now passes.
Through the bff, the browser never sees the challenge itself. StepUpChallengeMapper reads it and the BFF answers
401 with a problem of type urn:problem:documents:step-up-required carrying acrValues and maxAge
(StepUpProblemMapper keeps them within what the login accepts). The SPA then navigates to
GET /bff/login?returnTo=…&acrValues=…&maxAge=…, and StepUpAuthorizationRequestResolver adds acr_values and
max_age to the next authorization request; see Authorization code with PKCE through the BFF and
Login pages and the BFF.
/**
* Checks the step-up parameters of a request.
*
* @param request the request.
* @return always {@code null}: this converter only vetoes requests.
* @throws ReauthenticationRequiredException if {@code max_age} is exceeded.
* @throws SecondFactorRequiredException if the requested {@code acr_values} are not reached.
*/
@Override
public Authentication convert(final HttpServletRequest request) {
final var user = SecurityContextHolder.getContext().getAuthentication();
if (!MfaAuthorizationManager.isUser(user)) {
return null;
}
final var authTime = factorTimeline.authTime(user);
if (authTime.isEmpty()) {
return null;
}
if (maxAgeExceeded(request.getParameter(MAX_AGE_PARAMETER), authTime.get())) {
throw new ReauthenticationRequiredException();
}
if (!acrReached(request.getParameter(ACR_VALUES_PARAMETER), factorTimeline.isMultiFactor(user))) {
throw SecondFactorRequiredException.forStepUp();
}
return null;
}
/**
* Guards the API operations that remove or reset a second factor (disabling the authenticator app, generating new
* recovery codes, revoking a trusted device): a stolen token, or a session left open, must not be enough to weaken the
* account. While the account has a confirmed second factor, the bearer token must show a multi-factor sign-in
* ({@code acr} {@value AuthenticationContextClass#MULTI_FACTOR}) whose {@code auth_time} is within
* {@code authserver.mfa.step-up-max-age}; otherwise an {@link InsufficientUserAuthenticationException} asks the client
* to step up (RFC 9470). An account without a second factor cannot step up, so it is not asked to. The controllers call
* it first; the {@code /api/**} chain itself is not changed.
*/
@Component
@RequiredArgsConstructor
public class StepUpGuard {
/** Tells whether the account has a confirmed second factor. */
private final HasConfirmedSecondFactorUseCase hasConfirmedSecondFactorUseCase;
/** Multi-factor settings, with the maximum age of the sign-in. */
private final MfaProperties mfaProperties;
/** Clock the age of the sign-in is measured with. */
private final Clock clock;
/**
* Requires a recent multi-factor sign-in from the bearer token of the current request.
*
* @param userId identifier of the account the operation acts on.
* @throws InsufficientUserAuthenticationException if the account has a confirmed second factor and the token does
* not show a recent enough multi-factor sign-in.
*/
public void requireRecentMultiFactor(final UUID userId) {
if (!hasConfirmedSecondFactorUseCase.execute(userId)) {
return;
}
final var maxAge = mfaProperties.stepUpMaxAge();
final var authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof JwtAuthenticationToken token)
|| !isRecentMultiFactor(token.getToken(), maxAge)) {
throw new InsufficientUserAuthenticationException(AuthenticationContextClass.MULTI_FACTOR, maxAge);
}
}
/**
* Tells whether a token shows a multi-factor sign-in that is recent enough.
*
* @param jwt the bearer token.
* @param maxAge maximum age of the sign-in.
* @return {@code true} when {@code acr} is the multi-factor class and {@code auth_time} is at most {@code maxAge}
* old (and not in the future).
*/
private boolean isRecentMultiFactor(final Jwt jwt, final Duration maxAge) {
if (!AuthenticationContextClass.MULTI_FACTOR.equals(jwt.getClaimAsString(IdTokenClaimNames.ACR))) {
return false;
}
final var authTime = jwt.getClaimAsInstant(IdTokenClaimNames.AUTH_TIME);
if (authTime == null) {
return false;
}
final var age = Duration.between(authTime, clock.instant());
return !age.isNegative() && age.compareTo(maxAge) <= 0;
}
}
@RequiredArgsConstructor
public class StepUpAccessDeniedHandler implements AccessDeniedHandler {
/** Handler of every denial that is not a step-up requirement. */
private final AccessDeniedHandler delegate;
/** Step-up policy, whose values are advertised in the challenge. */
private final StepUpProperties properties;
@Override
public void handle(final HttpServletRequest request, final HttpServletResponse response,
final AccessDeniedException accessDeniedException) throws IOException, ServletException {
if (accessDeniedException instanceof AuthorizationDeniedException denied
&& denied.getAuthorizationResult() instanceof StepUpRequiredDecision) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer error=\"insufficient_user_authentication\", "
+ "acr_values=\"" + properties.acrValues() + "\", max_age=\""
+ properties.maxAge().toSeconds() + "\"");
return;
}
delegate.handle(request, response, accessDeniedException);
}
}
Decision on the authorization request
API challenge and retry
Tokens and claims
-
acr:urn:irurueta:acr:mfawhen the session is multi-factor (MfaPolicy.isMultiFactor: two distinct reported factors, or one factor that is multi-factor alone), otherwiseurn:irurueta:acr:pwd(MfaClaimsContributor). The same rule decides the authorization request converter, so the claims and the step-up checks always agree. A trusted provider’s multi-factor sign-in is multi-factor alone (see Social login and identity brokering). -
amr: the RFC 8176 values of the presented factors plusmfa, for examplepwd,otp,mfa. -
auth_time: the time the earliest primary factor was presented, written byMfaClaimsContributoron access tokens and by the framework on ID tokens. A second factor added later does not move it, somax_ageand the APIs' age limit measure the sign-in itself. -
The challenge:
WWW-Authenticate: Bearer error="insufficient_user_authentication", acr_values="urn:irurueta:acr:mfa", max_age="300"(the configured age in seconds).
By design:
-
A remembered (trusted) device is never reported and never satisfies a step-up.
-
A passkey or a certificate alone is a strong factor, so it satisfies the sign-in policy, but it proves one thing (user verification of a passkey is only preferred; a certificate is possession of a key), so its
acris the password class: a step-up asks it for a second factor. -
A sign-in at a provider with
trust-mfathat reportedmfa(FACTOR_FEDERATED_MFA) is multi-factor alone: it getsacrurn:irurueta:acr:mfaand passes a step-up (acr_values,StepUpGuard, the resource server and the phone page) without a local second factor, as long as it is recent enough.
How it is tested
-
StepUpIT(auth-server/boot):acr_valuesasking for the multi-factor class requires the second factor, the password class is satisfied by the password, and an exceededmax_ageforces a new sign-in with a newerauth_time. -
TotpApiIT(auth-server/boot): the account API answers the step-up challenge to a token without a recent multi-factor sign-in. -
TrustedDeviceIT(auth-server/boot): a trusted device skips the second factor at sign-in. -
SocialLoginIT(auth-server/boot): unlinking an identity needs a step-up token. -
StepUpDeletionIT(resource-server/boot): a password-only or stale token is challenged, a recent multi-factor token deletes, and listing is never challenged. -
SocialTrustedProviderIT(auth-server/boot): after a trusted provider’s multi-factor sign-in,acr_valuesasking for the multi-factor class issues the code without a second factor. -
BffEndToEndIT(e2e-tests): a password-only session’s deletion through the BFF answers the step-up problem, and the step-up login reaches the second-factor page.