OpenID Connect sign-in
| This documentation was generated with the assistance of AI. Please report any inaccuracies. |
OpenID Connect adds an identity layer to the authorization code flow: a client that asks for the openid scope gets an
ID token that tells it who signed in, how and when, and may call the UserInfo endpoint for profile claims. auth-server
enables OpenID Connect on its protocol chain (server.oidc(…) in SecurityConfig.authorizationServerSecurityFilterChain),
publishes its metadata at the OpenID Connect discovery and RFC 8414 endpoints, and signs every token with RSA keys that
are persisted in PostgreSQL and rotated, publishing the public halves at the JWKS endpoint. Custom claims (roles,
tenant, aud, amr, acr, auth_time, idp) are added by IssuedTokenClaims and the JwtClaimsContributor beans.
At a glance
| Item | Value |
|---|---|
Actors |
User and browser, a relying party (in this repository the |
Clients |
Any client with the |
Preconditions |
The issuer is |
Endpoints |
|
Steps
-
The relying party reads
/.well-known/openid-configuration(public, no session needed). It names theissuer, the authorization, token, JWKS, UserInfo and end-session endpoints, the supported scopes, response types, client authentication methods and signing algorithms. Feature customizers add to it, for exampleClientAuthProtocolChainCustomizeraddsmtls_endpoint_aliaseswhenauthserver.x509.portis set, andregistration_endpointappears only with dynamic registration enabled. -
It redirects the browser to
/oauth2/authorizewithresponse_type=code,scope=openid …,state,nonceand a PKCE challenge (see Authorization code with PKCE through the BFF). It may addacr_valuesandmax_age, whichStepUpAuthorizationRequestConverterreads (see Step-up authentication). -
The user signs in and, if needed, proves a second factor and consents. Each method grants a
FACTOR_*authority, which later becomesamrandacr. -
The relying party exchanges the code at
/oauth2/tokenand receives an access token, a refresh token (confidential clients) and an ID token. -
When Spring Authorization Server encodes each JWT,
RolesTenantAudienceTokenCustomizercallsIssuedTokenClaims, which addsroles,tenantandaudto access tokens only, then runs everyJwtClaimsContributoron access and ID tokens:MfaClaimsContributor(amr,acr, andauth_timeon access tokens),IdpClaimsContributor(idpafter a social sign-in) andTokenExchangeAudienceContributor(exchanged tokens only). TheJwtEncodersigns with theACTIVEkey ofsigning_keys. -
The relying party fetches
/oauth2/jwksand verifies the ID token signature,iss,aud(its client id),expandnonce. The key set (DatabaseJwkSourceConfiguration) contains theACTIVEandNEXTkeys and everyRETIREDkey still within its effective retention, cached forauthserver.keys.jwks-cache-ttl(defaultPT30S), so a token signed before a rotation keeps validating. -
Optionally, it calls
/userinfowith the access token as a bearer token. The framework checks the token and itsopenidscope andUserInfoMapper(registered byUserInfoConfigurationthrough aProtocolChainCustomizer) builds the answer from the user’s account, limited to the granted scopes.
What the UserInfo endpoint returns depends on the granted scopes:
The UserInfo mapping:
/**
* Builds the OpenID Connect UserInfo response from the account of the user, limited to the granted scopes: the
* {@code sub} claim always; {@code preferred_username}, {@code roles} and {@code tenant} with the {@code profile}
* scope; {@code email} and {@code email_verified} with the {@code email} scope.
*/
@Component
@RequiredArgsConstructor
public class UserInfoMapper implements Function<OidcUserInfoAuthenticationContext, OidcUserInfo> {
/** Scope that grants the profile claims. */
public static final String PROFILE_SCOPE = "profile";
/** Scope that grants the e-mail claims. */
public static final String EMAIL_SCOPE = "email";
/** Finds the account of the user. */
private final FindUserAccountUseCase findUserAccountUseCase;
@Override
public OidcUserInfo apply(final OidcUserInfoAuthenticationContext context) {
final var username = context.getAuthorization().getPrincipalName();
final var scopes = context.getAccessToken().getScopes();
final var claims = new HashMap<String, Object>();
claims.put(StandardClaimNames.SUB, username);
findUserAccountUseCase.execute(username).ifPresent(account -> {
if (scopes.contains(PROFILE_SCOPE)) {
claims.put(StandardClaimNames.PREFERRED_USERNAME, account.username());
claims.put(IssuedTokenClaims.ROLES_CLAIM, account.authorities());
claims.put(IssuedTokenClaims.TENANT_CLAIM, account.tenant());
}
if (scopes.contains(EMAIL_SCOPE) && account.email() != null) {
claims.put(StandardClaimNames.EMAIL, account.email());
claims.put(StandardClaimNames.EMAIL_VERIFIED, account.emailVerified());
}
});
return new OidcUserInfo(claims);
}
}
The amr / acr / auth_time contributor:
/**
* 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());
}
}
}
Tokens and claims
| Claim | ID token | Access token (JWT) |
|---|---|---|
|
Yes; |
Yes; lifetime from the client (10 minutes for the seeded clients) |
|
The client id |
The client’s |
|
Set by the framework ( |
No |
|
Set by the framework from the session |
|
|
No |
The granted scopes |
|
No (they are in UserInfo with |
Yes, for user grants; never for |
|
RFC 8176 values of the factors presented ( |
Same |
|
|
Same |
|
After a social sign-in ( |
Same |
UserInfo answers sub always, preferred_username, roles and tenant with profile, email and
email_verified with email. The seeded clients do not have the email scope, so they get no e-mail claims.
How it is tested
-
auth-server/bootAuthorizationCodePkceIT: the access and ID tokens validate against/oauth2/jwks; the ID token’ssub,aud,nonceandissare checked. -
auth-server/bootSecurityITandSecurityConfigIT:/.well-known/openid-configurationand/oauth2/jwksare public and the issuer is the configured one. -
auth-server/bootTokenFlowIT: access token claims (aud,roles,tenant,scope), UserInfo withprofileandemail, and UserInfo refused without or with an invalid token. -
auth-server/bootKeyRotationIT: the key set in each state of the rotation lifecycle, and a token signed before a rotation stays valid until its key is removed. -
auth-server/bootStepUpIT:acr_valuesandmax_ageon the authorization request. -
auth-server/bootParIT: the discovery metadata advertises the PAR endpoint only when it is enabled. -
e2e-testsPasskeyEndToEndIT:amrreportshwkalone, orpwd,hwkandmfa.