Social login and identity brokering

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

With social login the authorization server is both an authorization server and a client. Inside the user’s own authorization code flow (the client application asked this server for a code), the user picks Google, Microsoft Entra ID, Apple or GitHub on the login page; this server then runs a second authorization code flow as an OpenID Connect client (Google, Entra ID, Apple) or a plain OAuth 2.0 client (GitHub) of that provider, through Spring Security’s oauth2Login(…​). The provider’s answer is resolved to a local account (an existing link, a link by verified e-mail, or a new account provisioned just in time), a federated factor is granted, and the original authorization request resumes. The client application only ever talks to this server and receives tokens whose sub is the local user name, with an idp claim naming the provider.

At a glance
  • Actors: the user and their browser, the client application (for example the bff), this authorization server (acting as the client of the provider) and the external identity provider.

  • Preconditions: a provider is enabled only when authserver.social.providers.<id>.client-id has text (SocialProvidersCondition); secrets come only from environment variables (AUTHSERVER_SOCIAL_*). Apple also needs team-id, key-id and private-key; Entra ID takes tenant and allowed-tenants. trust-mfa (default false) lets a provider’s own multi-factor sign-in count. With no provider configured there is no social bean at all.

  • Endpoints: GET /login (provider buttons), GET /oauth2/authorization/{registrationId} (start), /login/oauth2/code/{registrationId} (callback, a POST for Apple’s form_post), GET /account/identities and POST /account/identities/link (explicit link), GET /api/account/identities and DELETE /api/account/identities/{id} (account API). The provider’s own endpoints are called server to server: the token endpoint, the JWKS for ID tokens and, for GitHub, /user and /user/emails.

Steps

Brokered sign-in

  1. The client sends the browser to GET /oauth2/authorize. Nobody is signed in, so the request is saved and the browser goes to GET /login.

  2. SocialLoginMethodFragment (rendered by templates/login-social.html) shows one link per configured provider, to GET /oauth2/authorization/{registrationId}. SocialChainCustomizer enabled oauth2Login with the server’s own /login page, so a single provider never auto-redirects.

  3. Spring Security redirects the browser to the provider’s authorization endpoint with its own state and, for OpenID Connect, a nonce. ClientRegistrationMapper built the registrations from SocialProperties, with the redirect URI {baseUrl}/login/oauth2/code/{registrationId}. For Apple, AppleAuthorizationRequestCustomizer asks for response_mode=form_post.

  4. The user signs in at the provider, which redirects (or, for Apple, posts) back to /login/oauth2/code/{registrationId} with a code.

  5. This server exchanges the code at the provider’s token endpoint. Apple’s client_secret is an ES256 JWT built by AppleClientSecretGenerator and swapped in by AppleTokenRequestCustomizer. An Entra ID token is checked by EntraIssuerValidator (installed by IdTokenValidatorFactory) for the iss of its own tid.

  6. FederatedOidcUserService (Google, Entra ID, Apple) or FederatedOAuth2UserService (GitHub, whose verified primary address comes from /user/emails through the VerifiedEmailLookup port, implemented by GitHubVerifiedEmailLookup) extracts the subject, the e-mail and whether the provider verified it (for Entra ID only email_verified or xms_edov count), and calls FederatedAccountResolver.

  7. FederatedAccountResolver calls ResolveFederatedLoginUseCase (see Account resolution), then loads the account through AccountStatusUserDetailsService. Any refusal becomes the OAuth 2.0 error access_denied, and FederatedAuthenticationFailureHandler sends the browser to /login?error. FederatedUserMapper builds the principal, whose name is the local user name.

  8. FederatedAuthenticationSuccessHandler asks FederatedFactorSelector for the factor, grants it through FactorGrantor, saves the security context and resumes the saved /oauth2/authorize request.

  9. The multi-factor policy applies as for any primary factor (see Authentication methods inside the authorization code flow): with FACTOR_FEDERATED a user who requires MFA is sent to GET /login/second-factor; with FACTOR_FEDERATED_MFA the policy is already satisfied, and because that factor is multi-factor alone (AuthenticationFactor.multiFactor) a request with acr_values for the multi-factor class is satisfied too. The code is then issued to the client.

/**
 * Finds the local account of a sign-in with an external provider and refuses it unless that account may sign in.
 *
 * <p>The use case finds, links or provisions the account and refuses a disabled one before it links anything; the
 * account is then loaded through the status-checking user service as well (the rules of
 * {@code AccountStatusUserDetailsService}: a disabled, locked or expired account is refused, exactly as the password
 * and passkey sign-ins refuse it). Every refusal is the same {@code access_denied} error, which the login chain turns
 * into the generic failure of the login page, so the answer never says whether an account exists or why it was
 * refused.
 *
 * <p>When the signed-in user asked to link this provider ({@link PendingIdentityLinks}), the identity is linked to
 * that account through {@link LinkIdentityUseCase} instead: nothing is resolved by e-mail address or provisioned, and
 * an identity that belongs to another account is refused with {@link #LINK_REFUSED}, which the failure handler sends
 * back to the identities page.
 */
@RequiredArgsConstructor
public class FederatedAccountResolver {

    /** Error description of every refusal. */
    static final String REFUSED = "The sign-in with the external provider was refused";

    /** Error code of a refused link: the identity belongs to another account. */
    public static final String LINK_REFUSED = "identity_link_refused";

    /** Error description of a refused link. */
    static final String LINK_REFUSED_DESCRIPTION = "The identity is linked to another account";

    /** Use case that finds, links or provisions the account. */
    private final ResolveFederatedLoginUseCase resolveFederatedLoginUseCase;

    /** Loads the account, refusing one that may not sign in. */
    private final UserDetailsService accountStatusUserDetailsService;

    /** Use case that links an identity to the signed-in account. */
    private final LinkIdentityUseCase linkIdentityUseCase;

    /** The link markers of the explicit link flow. */
    private final PendingIdentityLinks pendingIdentityLinks;

    /**
     * Resolves a sign-in.
     *
     * @param provider      the provider that authenticated the user.
     * @param subject       the provider's stable identifier of the user.
     * @param email         e-mail address the provider reported, or {@code null}.
     * @param emailVerified whether the provider vouches for the address.
     * @return the local account, which may sign in; for a link, the signed-in account.
     * @throws OAuth2AuthenticationException if the sign-in is refused: the provider did not verify the address, the
     *                                       address belongs to an unverified account, or the account is disabled,
     *                                       locked or expired; or if a link is refused because the identity belongs to
     *                                       another account.
     */
    public UserDetails resolve(
            final IdentityProvider provider, final String subject, final String email, final boolean emailVerified) {
        final var link = pendingIdentityLinks.consume(provider);
        if (link.isPresent()) {
            return link(link.get(), provider, subject, email);
        }
        try {
            final var login = resolveFederatedLoginUseCase.execute(provider, subject, email, emailVerified);
            return accountStatusUserDetailsService.loadUserByUsername(login.account().username());
        } catch (final FederatedLoginRefusedException | AuthenticationException e) {
            throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.ACCESS_DENIED, REFUSED, null), e);
        }
    }

    /**
     * Links an identity to the signed-in account that asked for it.
     *
     * @param link     the link marker.
     * @param provider the provider that authenticated the user.
     * @param subject  the provider's stable identifier of the user.
     * @param email    e-mail address the provider reported, or {@code null}.
     * @return the signed-in account.
     * @throws OAuth2AuthenticationException if the identity belongs to another account, or the account may no longer
     *                                       sign in.
     */
    private UserDetails link(final PendingIdentityLink link, final IdentityProvider provider, final String subject,
                             final String email) {
        try {
            linkIdentityUseCase.execute(link.userId(), link.username(), provider, subject, email);
            return accountStatusUserDetailsService.loadUserByUsername(link.username());
        } catch (final FederatedIdentityAlreadyLinkedException | AuthenticationException e) {
            throw new OAuth2AuthenticationException(
                    new OAuth2Error(LINK_REFUSED, LINK_REFUSED_DESCRIPTION, null), e);
        }
    }
}
sequenceDiagram autonumber participant B as Browser participant C as Client application participant AS as Authorization server participant IdP as Identity provider C->>B: redirect to /oauth2/authorize B->>AS: GET /oauth2/authorize AS-->>B: 302 to /login (request saved) B->>AS: GET /oauth2/authorization/google AS-->>B: 302 to provider with state and nonce B->>IdP: authorization request IdP->>IdP: user signs in at the provider IdP-->>B: 302 to /login/oauth2/code/google with code B->>AS: GET /login/oauth2/code/google with code and state AS->>IdP: POST token request with code and client credentials IdP-->>AS: ID token and access token AS->>AS: validate ID token, FederatedOidcUserService AS->>AS: ResolveFederatedLoginUseCase (link, provision or refuse) AS->>AS: grant FACTOR_FEDERATED or FACTOR_FEDERATED_MFA AS-->>B: 302 to saved /oauth2/authorize B->>AS: GET /oauth2/authorize AS->>AS: MFA policy, maybe /login/second-factor AS-->>B: 302 to client redirect_uri with code B->>C: code C->>AS: POST /oauth2/token AS-->>C: tokens with local sub, idp and amr fed

Account resolution

ResolveFederatedLoginUseCase first takes FederatedIdentityRepository.lockSubject(provider, subject), a PostgreSQL transaction-level advisory lock, so two concurrent first sign-ins of the same person are serialized and the second finds the link the first stored. Then:

  1. An identity already linked by (provider, subject) in federated_identities signs in to its account, if FederatedLinkingPolicy.maySignIn allows it (the account is enabled); the stored e-mail and last-use time are updated.

  2. Otherwise the provider must have verified a non-blank e-mail (FederatedLinkingPolicy.mayProvision); if not, the sign-in is refused and nothing is linked.

  3. An account with that e-mail is linked only when that account has verified the address too (FederatedLinkingPolicy.mayLinkByEmail) and may sign in. A pre-registered account with an unverified address is refused, so nobody can take it over by registering the address first.

  4. With no account for the address, a password-less account is provisioned just in time: its user name is the e-mail (or <provider>-<uuid> when that is taken or too long), its random password is flagged in user_passwords.generated so it does not count as a sign-in method.

Every link is audited as IDENTITY_LINKED.

flowchart TD A["Provider answer: subject, e-mail, verified flag"] --> L["lockSubject(provider, subject)"] L --> B{"Identity linked for provider and subject?"} B -- yes --> E1{"Account enabled?"} E1 -- yes --> S["Sign in to the linked account"] E1 -- no --> X["Refuse: access_denied"] B -- no --> C{"Provider verified a non-blank e-mail?"} C -- no --> X C -- yes --> D{"Account with that e-mail exists?"} D -- yes --> F{"Account verified the e-mail and is enabled?"} F -- yes --> K["Link identity to that account (IDENTITY_LINKED)"] F -- no --> X D -- no --> P["Provision account just in time, generated password"] P --> K K --> S

A user whose provider address differs from the account’s, or is not verified, links the provider after signing in:

  1. GET /account/identities (IdentitiesPageController, guarded by IdentitiesPageChainCustomizer behind the MFA policy) lists the linked identities and one button per configured provider.

  2. POST /account/identities/link (form field provider) stores a PendingIdentityLink in the session through PendingIdentityLinks (used once, valid for five minutes) and redirects to /oauth2/authorization/{registrationId}.

  3. When the provider answers, FederatedAccountResolver consumes the marker (same provider, not expired, session still signed in as that account) and calls LinkIdentityUseCase for that account instead of resolving by e-mail.

  4. On success FederatedAuthenticationSuccessHandler puts the session’s previous authentication back, grants no factor and redirects to /account/identities?status=linked. An identity linked to another account raises FederatedIdentityAlreadyLinkedException, mapped to the error identity_link_refused, and the browser returns to /account/identities?status=already-linked with the session unchanged.

Unlinking is on the bearer API: DELETE /api/account/identities/{id} (IdentityController) calls StepUpGuard first (see Step-up authentication) and is refused with 409 last-sign-in-method when it would remove the last way to sign in.

Tokens and claims

/**
 * Decides which factor a federated sign-in proved: the strong one when the provider is trusted for its multi-factor
 * authentication ({@code authserver.social.providers.<id>.trust-mfa}) and its upstream {@code amr} contains
 * {@code mfa}, the ordinary one otherwise. An upstream claim the server was not told to trust is never believed.
 */
@RequiredArgsConstructor
public class FederatedFactorSelector {

    /** Settings of the providers, for the trust. */
    private final SocialProperties properties;

    /** Reads the upstream {@code amr}. */
    private final FederatedUserMapper userMapper;

    /**
     * Selects the factor of a sign-in.
     *
     * @param token the authentication of the sign-in.
     * @return {@link FederatedFactor#STRONG_AUTHORITY} or {@link FederatedFactor#AUTHORITY}.
     */
    public String authorityOf(final OAuth2AuthenticationToken token) {
        return IdentityProvider.fromId(token.getAuthorizedClientRegistrationId())
                .map(properties::trust)
                .filter(trust -> trust.isStrong(userMapper.upstreamAmr(Objects.requireNonNull(token.getPrincipal()))))
                .map(trust -> FederatedFactor.STRONG_AUTHORITY)
                .orElse(FederatedFactor.AUTHORITY);
    }
}
  • Factor: FACTOR_FEDERATED (PRIMARY) by default. FACTOR_FEDERATED_MFA (PRIMARY_STRONG) only when the provider has trust-mfa: true and its upstream amr contains mfa; an untrusted provider’s amr is never believed. Both report amr fed and are never held together.

  • sub: the local user name, never the provider’s subject.

  • idp: the registration id of the provider (google, microsoft, apple or github), written by IdpClaimsContributor.

  • amr: fed (by MfaClaimsContributor), plus mfa and the other factor when a second factor was presented. For the strong factor MfaClaimsContributor writes fed and mfa, then IdpClaimsContributor merges the upstream amr values after them, each once (for example fed, mfa, pwd).

  • acr: urn:irurueta:acr:mfa for the strong factor or after a second factor, otherwise urn:irurueta:acr:pwd. It is always written by MfaClaimsContributor (MfaPolicy.isMultiFactor); IdpClaimsContributor never sets it.

  • auth_time: the time the federated factor was granted (on access tokens; the framework sets it on ID tokens).

/**
 * Adds to the tokens of a user who signed in with an external provider the claim {@code idp} (the registration id of
 * the provider). The {@code sub} is the local account's username, because the principal's name is (see
 * {@link FederatedUserMapper}), so a token of a federated sign-in is indistinguishable from any other in what it says
 * about the user.
 *
 * <p>When the provider is trusted for its multi-factor authentication and proved it (the strong factor,
 * {@link FederatedFactor#STRONG_AUTHORITY}), the upstream {@code amr} values are added to the {@code amr} claim the
 * {@link com.irurueta.authserver.authorization.api.web.mfa.MfaClaimsContributor} wrote (each value once, so the
 * repeated ones of the factor and of the provider are listed once, and {@code mfa} is there exactly once). The
 * {@code acr} is not set here: the strong factor is {@link
 * com.irurueta.authserver.authorization.domain.mfa.AuthenticationFactor#multiFactor() multi-factor alone}, so the
 * multi-factor contributor already wrote the multi-factor class, from the same rule the step-up checks use. The
 * upstream {@code amr} of a provider that is not trusted is never copied: it would claim a strength the server did not
 * accept.
 */
@Component
@Order(IdpClaimsContributor.ORDER)
@RequiredArgsConstructor
public class IdpClaimsContributor implements JwtClaimsContributor {

    /** Order of the contributor: after the multi-factor one, whose {@code amr} it extends. */
    public static final int ORDER = 110;

    /** Name of the claim that says which provider authenticated the user. */
    public static final String IDP_CLAIM = "idp";

    /** Reads the upstream {@code amr}. */
    private final FederatedUserMapper userMapper;

    /**
     * Adds the claims.
     *
     * @param context the token context.
     * @param claims  the claims, which this method extends.
     */
    @Override
    public void contribute(final OAuth2TokenContext context, final Map<String, Object> claims) {
        if (!(context.getPrincipal() instanceof final OAuth2AuthenticationToken token)) {
            return;
        }
        claims.put(IDP_CLAIM, token.getAuthorizedClientRegistrationId());
        final var strong = token.getAuthorities().stream().map(GrantedAuthority::getAuthority)
                .anyMatch(FederatedFactor.STRONG_AUTHORITY::equals);
        if (!strong) {
            return;
        }
        // a mutable list on purpose: the authorization store only deserializes allow-listed types
        final var amr = new ArrayList<String>(existingAmr(claims));
        final var upstream = userMapper.upstreamAmr(Objects.requireNonNull(token.getPrincipal()));
        upstream.stream().filter(value -> !amr.contains(value)).forEach(amr::add);
        claims.put(IdTokenClaimNames.AMR, amr);
    }

    /**
     * Reads the {@code amr} already in the claims.
     *
     * @param claims the claims.
     * @return its values; empty when there is none.
     */
    private static List<String> existingAmr(final Map<String, Object> claims) {
        return claims.get(IdTokenClaimNames.AMR) instanceof final List<?> values
                ? values.stream().map(String::valueOf).distinct().toList() : List.of();
    }
}

How it is tested

The provider is a WireMock fake, so no test calls a real identity provider.

  • SocialLoginIT (auth-server/boot): provisioning, linking by verified e-mail, refusal of unverified addresses and disabled accounts, GitHub’s verified primary address, the sub, idp and amr claims, the second factor for an untrusted provider, unlinking with step-up and the last-method rule, and the explicit link flow.

  • SocialTrustedProviderIT (auth-server/boot): a trusted provider reporting mfa skips the second factor and its upstream factors are reported; without mfa or amr the second factor is asked.

  • SocialEntraMultiTenantIT and SocialEntraSingleTenantIT (auth-server/boot): the Entra ID issuer and tenant checks.

  • SocialLoginConfigurationIT (auth-server/boot): which providers are enabled from the configuration.

  • JdbcFederatedIdentityRepositoryIT, JdbcGeneratedPasswordRepositoryIT and JdbcSignInMethodsLockIT (auth-server/infrastructure/persistence): the identity table, the generated-password flag and the locks.