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 bff, through Spring Security’s oauth2Login), auth-server.

Clients

Any client with the openid scope: the seeded bff and spa-public both have it. The device grant’s device-client has none (Spring Authorization Server refuses openid in device requests).

Preconditions

The issuer is spring.security.oauth2.authorizationserver.issuer (AUTHSERVER_ISSUER_URL, default http://localhost:9000). Signing keys need the key-encryption secret (authserver.keys.encryption.password and .salt, generated per machine by DevKeyEncryptionSecret under the dev profile). Nothing else to enable.

Endpoints

GET /.well-known/openid-configuration (OpenID Connect Discovery), GET /.well-known/oauth-authorization-server (RFC 8414), GET /oauth2/jwks, GET /oauth2/authorize, POST /oauth2/token, GET or POST /userinfo, /connect/logout (see Logout) and, when enabled, /connect/register (see Dynamic client registration).

Steps

  1. The relying party reads /.well-known/openid-configuration (public, no session needed). It names the issuer, 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 example ClientAuthProtocolChainCustomizer adds mtls_endpoint_aliases when authserver.x509.port is set, and registration_endpoint appears only with dynamic registration enabled.

  2. It redirects the browser to /oauth2/authorize with response_type=code, scope=openid …​, state, nonce and a PKCE challenge (see Authorization code with PKCE through the BFF). It may add acr_values and max_age, which StepUpAuthorizationRequestConverter reads (see Step-up authentication).

  3. The user signs in and, if needed, proves a second factor and consents. Each method grants a FACTOR_* authority, which later becomes amr and acr.

  4. The relying party exchanges the code at /oauth2/token and receives an access token, a refresh token (confidential clients) and an ID token.

  5. When Spring Authorization Server encodes each JWT, RolesTenantAudienceTokenCustomizer calls IssuedTokenClaims, which adds roles, tenant and aud to access tokens only, then runs every JwtClaimsContributor on access and ID tokens: MfaClaimsContributor (amr, acr, and auth_time on access tokens), IdpClaimsContributor (idp after a social sign-in) and TokenExchangeAudienceContributor (exchanged tokens only). The JwtEncoder signs with the ACTIVE key of signing_keys.

  6. The relying party fetches /oauth2/jwks and verifies the ID token signature, iss, aud (its client id), exp and nonce. The key set (DatabaseJwkSourceConfiguration) contains the ACTIVE and NEXT keys and every RETIRED key still within its effective retention, cached for authserver.keys.jwks-cache-ttl (default PT30S), so a token signed before a rotation keeps validating.

  7. Optionally, it calls /userinfo with the access token as a bearer token. The framework checks the token and its openid scope and UserInfoMapper (registered by UserInfoConfiguration through a ProtocolChainCustomizer) builds the answer from the user’s account, limited to the granted scopes.

sequenceDiagram autonumber participant RP as Relying party participant B as Browser participant A as auth-server participant DB as signing_keys RP->>A: GET /.well-known/openid-configuration A-->>RP: issuer and endpoint metadata RP-->>B: 302 to /oauth2/authorize scope=openid with nonce and PKCE B->>A: sign in, second factor and consent as needed A-->>B: 302 to redirect_uri with code B->>RP: code and state RP->>A: POST /oauth2/token A->>DB: sign with the ACTIVE key A-->>RP: access_token, refresh_token, id_token RP->>A: GET /oauth2/jwks A->>DB: ACTIVE, NEXT and retained RETIRED public keys A-->>RP: JWK set Note over RP: verify id_token signature, iss, aud, exp and nonce RP->>A: GET /userinfo with Bearer access token A-->>RP: sub and the claims the granted scopes allow

What the UserInfo endpoint returns depends on the granted scopes:

flowchart TD Start(["GET /userinfo"]) --> Token{"Valid bearer token with openid scope?"} Token -- "no bearer token" --> Login["302 to /login"] Token -- "invalid token" --> Unauth["401"] Token -- "yes" --> Sub["sub"] Sub --> Profile{"profile granted?"} Profile -- "yes" --> P["preferred_username, roles, tenant"] Profile -- "no" --> Email P --> Email{"email granted and address known?"} Email -- "yes" --> E["email, email_verified"] Email -- "no" --> Done(["answer"]) E --> Done

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)

iss, sub, iat, exp, jti

Yes; sub is the local username for every sign-in method; lifetime fixed by the framework at 30 minutes

Yes; lifetime from the client (10 minutes for the seeded clients)

aud

The client id

The client’s audiences setting (resource-server and auth-server for the seeded clients), else the client id

azp, nonce

Set by the framework (nonce when the request sent one)

No

sid, auth_time

Set by the framework from the session

auth_time by MfaClaimsContributor: epoch second of the primary factor

scope

No

The granted scopes

roles, tenant

No (they are in UserInfo with profile)

Yes, for user grants; never for client_credentials

amr

RFC 8176 values of the factors presented (pwd, otp, sms, hwk, fed, …​), plus mfa for a multi-factor sign-in

Same

acr

urn:irurueta:acr:pwd or urn:irurueta:acr:mfa

Same

idp

After a social sign-in (IdpClaimsContributor)

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/boot AuthorizationCodePkceIT: the access and ID tokens validate against /oauth2/jwks; the ID token’s sub, aud, nonce and iss are checked.

  • auth-server/boot SecurityIT and SecurityConfigIT: /.well-known/openid-configuration and /oauth2/jwks are public and the issuer is the configured one.

  • auth-server/boot TokenFlowIT: access token claims (aud, roles, tenant, scope), UserInfo with profile and email, and UserInfo refused without or with an invalid token.

  • auth-server/boot KeyRotationIT: 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/boot StepUpIT: acr_values and max_age on the authorization request.

  • auth-server/boot ParIT: the discovery metadata advertises the PAR endpoint only when it is enabled.

  • e2e-tests PasskeyEndToEndIT: amr reports hwk alone, or pwd, hwk and mfa.