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.
-
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-idhas text (SocialProvidersCondition); secrets come only from environment variables (AUTHSERVER_SOCIAL_*). Apple also needsteam-id,key-idandprivate-key; Entra ID takestenantandallowed-tenants.trust-mfa(defaultfalse) 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, aPOSTfor Apple’sform_post),GET /account/identitiesandPOST /account/identities/link(explicit link),GET /api/account/identitiesandDELETE /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,/userand/user/emails.
Steps
Brokered sign-in
-
The client sends the browser to
GET /oauth2/authorize. Nobody is signed in, so the request is saved and the browser goes toGET /login. -
SocialLoginMethodFragment(rendered bytemplates/login-social.html) shows one link per configured provider, toGET /oauth2/authorization/{registrationId}.SocialChainCustomizerenabledoauth2Loginwith the server’s own/loginpage, so a single provider never auto-redirects. -
Spring Security redirects the browser to the provider’s authorization endpoint with its own
stateand, for OpenID Connect, anonce.ClientRegistrationMapperbuilt the registrations fromSocialProperties, with the redirect URI{baseUrl}/login/oauth2/code/{registrationId}. For Apple,AppleAuthorizationRequestCustomizerasks forresponse_mode=form_post. -
The user signs in at the provider, which redirects (or, for Apple, posts) back to
/login/oauth2/code/{registrationId}with a code. -
This server exchanges the code at the provider’s token endpoint. Apple’s
client_secretis an ES256 JWT built byAppleClientSecretGeneratorand swapped in byAppleTokenRequestCustomizer. An Entra ID token is checked byEntraIssuerValidator(installed byIdTokenValidatorFactory) for theissof its owntid. -
FederatedOidcUserService(Google, Entra ID, Apple) orFederatedOAuth2UserService(GitHub, whose verified primary address comes from/user/emailsthrough theVerifiedEmailLookupport, implemented byGitHubVerifiedEmailLookup) extracts the subject, the e-mail and whether the provider verified it (for Entra ID onlyemail_verifiedorxms_edovcount), and callsFederatedAccountResolver. -
FederatedAccountResolvercallsResolveFederatedLoginUseCase(see Account resolution), then loads the account throughAccountStatusUserDetailsService. Any refusal becomes the OAuth 2.0 erroraccess_denied, andFederatedAuthenticationFailureHandlersends the browser to/login?error.FederatedUserMapperbuilds the principal, whose name is the local user name. -
FederatedAuthenticationSuccessHandlerasksFederatedFactorSelectorfor the factor, grants it throughFactorGrantor, saves the security context and resumes the saved/oauth2/authorizerequest. -
The multi-factor policy applies as for any primary factor (see Authentication methods inside the authorization code flow): with
FACTOR_FEDERATEDa user who requires MFA is sent toGET /login/second-factor; withFACTOR_FEDERATED_MFAthe policy is already satisfied, and because that factor is multi-factor alone (AuthenticationFactor.multiFactor) a request withacr_valuesfor 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);
}
}
}
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:
-
An identity already linked by
(provider, subject)infederated_identitiessigns in to its account, ifFederatedLinkingPolicy.maySignInallows it (the account is enabled); the stored e-mail and last-use time are updated. -
Otherwise the provider must have verified a non-blank e-mail (
FederatedLinkingPolicy.mayProvision); if not, the sign-in is refused and nothing is linked. -
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. -
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 inuser_passwords.generatedso it does not count as a sign-in method.
Every link is audited as IDENTITY_LINKED.
Explicit link from the identities page
A user whose provider address differs from the account’s, or is not verified, links the provider after signing in:
-
GET /account/identities(IdentitiesPageController, guarded byIdentitiesPageChainCustomizerbehind the MFA policy) lists the linked identities and one button per configured provider. -
POST /account/identities/link(form fieldprovider) stores aPendingIdentityLinkin the session throughPendingIdentityLinks(used once, valid for five minutes) and redirects to/oauth2/authorization/{registrationId}. -
When the provider answers,
FederatedAccountResolverconsumes the marker (same provider, not expired, session still signed in as that account) and callsLinkIdentityUseCasefor that account instead of resolving by e-mail. -
On success
FederatedAuthenticationSuccessHandlerputs the session’s previous authentication back, grants no factor and redirects to/account/identities?status=linked. An identity linked to another account raisesFederatedIdentityAlreadyLinkedException, mapped to the erroridentity_link_refused, and the browser returns to/account/identities?status=already-linkedwith 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 hastrust-mfa: trueand its upstreamamrcontainsmfa; an untrusted provider’samris never believed. Both reportamrfedand are never held together. -
sub: the local user name, never the provider’s subject. -
idp: the registration id of the provider (google,microsoft,appleorgithub), written byIdpClaimsContributor. -
amr:fed(byMfaClaimsContributor), plusmfaand the other factor when a second factor was presented. For the strong factorMfaClaimsContributorwritesfedandmfa, thenIdpClaimsContributormerges the upstreamamrvalues after them, each once (for examplefed,mfa,pwd). -
acr:urn:irurueta:acr:mfafor the strong factor or after a second factor, otherwiseurn:irurueta:acr:pwd. It is always written byMfaClaimsContributor(MfaPolicy.isMultiFactor);IdpClaimsContributornever 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, thesub,idpandamrclaims, 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 reportingmfaskips the second factor and its upstream factors are reported; withoutmfaoramrthe second factor is asked. -
SocialEntraMultiTenantITandSocialEntraSingleTenantIT(auth-server/boot): the Entra ID issuer and tenant checks. -
SocialLoginConfigurationIT(auth-server/boot): which providers are enabled from the configuration. -
JdbcFederatedIdentityRepositoryIT,JdbcGeneratedPasswordRepositoryITandJdbcSignInMethodsLockIT(auth-server/infrastructure/persistence): the identity table, the generated-password flag and the locks.
Specifications
-
OpenID Connect Core 1.0 (ID token,
nonce,amr,acr) -
RFC 6749, The OAuth 2.0 Authorization Framework (section 4.1, authorization code)