8000 Allow replacing existing federated identity link for same user (opt-in) by Oluwatobi-Mustapha · Pull Request #48176 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/documentation/release_notes/topics/27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ See the upgrading guide for details.

The `UPDATE_CREDENTIAL` events emitted by built-in required actions now carry the `credential_id` detail when a credential was created or updated in the {project_name} credential store, as the `REMOVE_CREDENTIAL` event already did. The detail is omitted when an external user-storage provider handles the update because there is no {project_name} credential ID to report.

== Audit event for identity provider link replacement

When client-initiated account linking replaces an existing link, {project_name} emits `FEDERATED_IDENTITY_OVERRIDE_LINK` with the previous and new external account IDs and usernames.
Overrides during first broker login now include both account IDs in the event as well.

= Themes

== Login and welcome UI upgraded to PatternFly 6
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,19 @@ to request linking to the identity provider with the alias `my-oidc-provider`, a
kc_action=idp_link:my-oidc-provider
----

==== Replacing an existing link

By default, if the current user already has a link to the identity provider, linking a different external account from that provider fails.
The user can still link the same external account again to refresh its token without enabling replacement.

You can allow this replacement for a specific identity provider by enabling the `allowLinkingWithExistingFederatedIdentity` configuration option.
When this option is enabled, client-initiated account linking replaces the user's existing link for that identity provider with the external account used during the new linking request.
The replacement applies only to an existing link owned by the same {project_name} user.
If the external account is already linked to a different {project_name} user, the linking request still fails.

This option applies to client-initiated account linking.
To replace a link during first-broker-login, use the link:{adminguide_link}#_override_existing_broker_link[Override existing broker link] first-broker-login authenticator.

==== Refreshing external tokens

If you use the external token generated by logging into the provider (such as a Facebook or GitHub token), you can refresh this token by re-initiating the account linking API.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public class IdentityProviderModel implements Serializable {
public static final String LEGACY_HIDE_ON_LOGIN_ATTR = "hideOnLoginPage";
public static final String LINK_ONLY = "linkOnly";
public static final String LOGIN_HINT = "loginHint";
public static final String ALLOW_LINKING_WITH_EXISTING_FEDERATED_IDENTITY = "allowLinkingWithExistingFederatedIdentity";
public static final String METADATA_DESCRIPTOR_URL = "metadataDescriptorUrl";
public static final String ORGANIZATION_ID = "organizationId";
public static final String ORGANIZATION_ID_NOT_NULL = "organizationIdNotNull";
Expand Down Expand Up @@ -329,6 +330,14 @@ public void setLoginHint(Boolean loginHint) {
setBooleanConfig(LOGIN_HINT, loginHint);
}

public boolean isAllowLinkingWithExistingFederatedIdentity() {
return getBooleanConfig(ALLOW_LINKING_WITH_EXISTING_FEDERATED_IDENTITY);
}

public void setAllowLinkingWithExistingFederatedIdentity(Boolean enabled) {
setBooleanConfig(ALLOW_LINKING_WITH_EXISTING_FEDERATED_IDENTITY, enabled);
}

public boolean isPassMaxAge() {
return getBooleanConfig(PASS_MAX_AGE);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
import org.keycloak.authentication.authenticators.broker.util.PostBrokerLoginConstants;
import org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext;
import org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator;
import org.keycloak.broker.oidc.OIDCIdentityProvider;
import org.keycloak.broker.provider.AuthenticationRequest;
import org.keycloak.broker.provider.BrokeredIdentityContext;
import org.keycloak.broker.provider.ExchangeTokenToIdentityProviderToken;
Expand Down Expand Up @@ -101,6 +102,7 @@
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.organization.utils.Organizations;
import org.keycloak.protocol.LoginProtocol;
import org.keycloak.protocol.ProtocolMapperUtils;
import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.OIDCProviderConfig;
Expand Down Expand Up @@ -767,9 +769,12 @@ public Response authenticated(BrokeredIdentityContext context) {
boolean shouldMigrateId = false;
// try to find the user using legacy ID
if (federatedUser == null && context.getLegacyId() != null) {
federatedIdentityModel = new FederatedIdentityModel(federatedIdentityModel, context.getLegacyId());
federatedUser = this.session.users().getUserByFederatedIdentity(this.realmModel, federatedIdentityModel);
shouldMigrateId = true;
FederatedIdentityModel legacyIdentity = new FederatedIdentityModel(federatedIdentityModel, context.getLegacyId());
federatedUser = this.session.users().getUserByFederatedIdentity(this.realmModel, legacyIdentity);
if (federatedUser != null) {
federatedIdentityModel = legacyIdentity;
shouldMigrateId = true;
}
}

// Check if linking was requested (for example by kc_action) or if we're authenticating
Expand Down Expand Up @@ -939,10 +944,9 @@ private Response afterFirstBrokerLogin(AuthenticationSessionModel authSession) {

// Add federated identity link here
if (!(federatedUser instanceof LightweightUserAdapter)) {
checkOverrideLink(authSession, federatedUser, providerAlias);

FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(context.getIdpConfig().getAlias(), context.getId(),
context.getUsername(), context.getToken());
checkOverrideLink(authSession, federatedUser, federatedIdentityModel);
try {
session.users().addFederatedIdentity(realmModel, federatedUser, federatedIdentityModel);
} catch (ModelDuplicateException de) {
Expand Down Expand Up @@ -989,23 +993,25 @@ private Response afterFirstBrokerLogin(AuthenticationSessionModel authSession) {
}
}

private void checkOverrideLink(AuthenticationSessionModel authSession, UserModel federatedUser, String providerAlias) {
private void checkOverrideLink(AuthenticationSessionModel authSession, UserModel federatedUser, FederatedIdentityModel newIdentity) {
String isOverride = authSession.getAuthNote(IdpConfirmOverrideLinkAuthenticator.OVERRIDE_LINK);
if (!Boolean.parseBoolean(isOverride)) {
return;
}

FederatedIdentityModel previous = session.users()
.getFederatedIdentity(realmModel, federatedUser, providerAlias);
.getFederatedIdentity(realmModel, federatedUser, newIdentity.getIdentityProvider());
if (previous == null) {
return;
}

session.users().removeFederatedIdentity(realmModel, federatedUser, providerAlias);
session.users().removeFederatedIdentity(realmModel, federatedUser, newIdentity.getIdentityProvider());

event.clone()
.event(EventType.FEDERATED_IDENTITY_OVERRIDE_LINK)
.detail(Details.IDENTITY_PROVIDER_USER_ID, newIdentity.getUserId())
.detail(Details.PREF_PREVIOUS + Details.IDENTITY_PROVIDER_USERNAME, previous.getUserName())
.detail(Details.PREF_PREVIOUS + Details.IDENTITY_PROVIDER_USER_ID, previous.getUserId())
.success();
}

Expand Down Expand Up @@ -1198,15 +1204,16 @@ private Response performAccountLinking(AuthenticationSessionModel authSession, B

UserModel authenticatedUser = authSession.getAuthenticatedUser();
authSession.setAuthenticatedUser(authenticatedUser);
String providerAlias = context.getIdpConfig().getAlias();

this.event.client(authSession.getClient())
.user(authenticatedUser)
.detail(Details.USERNAME, authenticatedUser.getUsername());

logger.debugf("Will try to link identity provider [%s] to user [%s]", context.getIdpConfig().getAlias(), authenticatedUser.getUsername());
logger.debugf("Will try to link identity provider [%s] to user [%s]", providerAlias, authenticatedUser.getUsername());

if (federatedUser != null && !authenticatedUser.getId().equals(federatedUser.getId())) {
logger.debugf("Cannot link user '%s' to identity provider '%s' . Other user '%s' already linked with the identity provider", authenticatedUser.getUsername(), context.getIdpConfig().getAlias(), federatedUser.getUsername());
logger.debugf("Cannot link user '%s' to identity provider '%s' . Other user '%s' already linked with the identity provider", authenticatedUser.getUsername(), providerAlias, federatedUser.getUsername());
String idpDisplayName = KeycloakModelUtils.getIdentityProviderDisplayName(session, context.getIdpConfig());
return redirectToErrorWhenLinkingFailed(authSession, Errors.FEDERATED_IDENTITY_EXISTS, Messages.IDENTITY_PROVIDER_ALREADY_LINKED, idpDisplayName);
}
Expand All @@ -1225,13 +1232,39 @@ private Response performAccountLinking(AuthenticationSessionModel authSession, B
return redirectToErrorWhenLinkingFailed(authSession, Errors.NOT_ALLOWED, Messages.FEDERATED_IDENTITY_BOUND_ORGANIZATION);
}

FederatedIdentityModel existingLinkForCurrentUser = federatedUser == null
? this.session.users().getFederatedIdentity(this.realmModel, authenticatedUser, providerAlias)
: null;
boolean replacedExistingLink = false;
if (federatedUser == null && existingLinkForCurrentUser != null) {
if (!context.getIdpConfig().isAllowLinkingWithExistingFederatedIdentity()) {
logger.debugf("Cannot link user '%s' to identity provider '%s'. Existing link found for this user and replacement is disabled", authenticatedUser.getUsername(), providerAlias);
String idpDisplayName = KeycloakModelUtils.getIdentityProviderDisplayName(session, context.getIdpConfig());
return redirectToErrorWhenLinkingFailed(authSession, Errors.FEDERATED_IDENTITY_EXISTS, Messages.IDENTITY_PROVIDER_ALREADY_LINKED_TO_CURRENT_USER, idpDisplayName);
}

// Use remove+add because some storage implementations do not update the broker user ID through updateFederatedIdentity.
this.session.users().removeFederatedIdentity(this.realmModel, authenticatedUser, providerAlias);
this.session.users().addFederatedIdentity(this.realmModel, authenticatedUser, newModel);
Comment thread
Oluwatobi-Mustapha marked this conversation as resolved.
Resolved
clearBrokerSessionTokens(authenticatedUser, providerAlias);
federatedUser = authenticatedUser;
replacedExistingLink = true;

if (isDebugEnabled()) {
logger.debugf("Replaced existing identity provider link [%s] for user [%s]. Previous federated user id [%s], new federated user id [%s]",
providerAlias, authenticatedUser.getUsername(), existingLinkForCurrentUser.getUserId(), newModel.getUserId());
}

emitOverriddenLinkEvent(authenticatedUser, existingLinkForCurrentUser, newModel);
}

if (federatedUser != null) {
if (Booleans.isTrue(context.getIdpConfig().isStoreToken())) {
FederatedIdentityModel oldModel = this.session.users().getFederatedIdentity(this.realmModel, federatedUser, context.getIdpConfig().getAlias());
if (!replacedExistingLink && Booleans.isTrue(context.getIdpConfig().isStoreToken())) {
FederatedIdentityModel oldModel = this.session.users().getFederatedIdentity(this.realmModel, federatedUser, providerAlias);
if (!ObjectUtil.isEqualOrBothNull(context.getToken(), oldModel.getToken())) {
this.session.users().updateFederatedIdentity(this.realmModel, federatedUser, newModel);
if (isDebugEnabled()) {
Comment thread
Oluwatobi-Mustapha marked this conversation as resolved.
Resolved
logger.debugf("Identity [%s] update with response from identity provider [%s].", federatedUser, context.getIdpConfig().getAlias());
logger.debugf("Identity [%s] update with response from identity provider [%s].", federatedUser, providerAlias);
}
}
}
Expand Down Expand Up @@ -1260,8 +1293,11 @@ private Response performAccountLinking(AuthenticationSessionModel authSession, B
// Maybe broker logout should be rather always skiped in case of broker-linking
UserSessionModel userSession = new AuthenticationSessionManager(session).getUserSession(authSession);
if (userSession != null && userSession.getNote(Details.IDENTITY_PROVIDER) == null) {
userSession.setNote(Details.IDENTITY_PROVIDER, context.getIdpConfig().getAlias());
userSession.setNote(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());
String externalProvider = userSession.getNote(UserAuthenticationIdentityProvider.EXTERNAL_IDENTITY_PROVIDER);
if (!replacedExistingLink || externalProvider == null || providerAlias.equals(externalProvider)) {
userSession.setNote(Details.IDENTITY_PROVIDER, providerAlias);
userSession.setNote(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());
}
}

authSession.setAuthNote(IdpLinkAction.IDP_LINK_STATUS, RequiredActionContext.KcActionStatus.SUCCESS.name());
Expand All @@ -1286,6 +1322,41 @@ private Response performAccountLinking(AuthenticationSessionModel authSession, B
return redirectAfterIDPLinking(authSession);
}

private void clearBrokerSessionTokens(UserModel user, String providerAlias) {
try (Stream<UserSessionModel> user);
Stream<UserSessionModel> offline = session.sessions().getOfflineUserSessionsStream(realmModel, user)) {
Stream.concat(online, offline).forEach(userSession -> {
String legacyProvider = Optional.ofNullable(userSession.getNote(Details.IDENTITY_PROVIDER))
.orElseGet(() -> userSession.getNote(UserAuthenticationIdentityProvider.EXTERNAL_IDENTITY_PROVIDER));
for (String note : ProtocolMapperUtils.BROKER_CREDENTIAL_NOTES) {
String providerNote = note + ":" + providerAlias;
if (userSession.getNote(providerNote) != null) {
userSession.removeNote(providerNote);
}
if (providerAlias.equals(legacyProvider) && userSession.getNote(note) != null) {
userSession.removeNote(note);
}
}
if (providerAlias.equals(userSession.getNote(OIDCIdentityProvider.EXCHANGE_PROVIDER))) {
userSession.removeNote(OIDCIdentityProvider.EXCHANGE_PROVIDER);
}
});
}
}

private void emitOverriddenLinkEvent(UserModel user, FederatedIdentityModel previousIdentity, FederatedIdentityModel newIdentity) {
event.clone()
.event(EventType.FEDERATED_IDENTITY_OVERRIDE_LINK)
.user(user)
.detail(Details.USERNAME, user.getUsername())
.detail(Details.IDENTITY_PROVIDER, newIdentity.getIdentityProvider())
.detail(Details.IDENTITY_PROVIDER_USERNAME, newIdentity.getUserName())
.detail(Details.IDENTITY_PROVIDER_USER_ID, newIdentity.getUserId())
.detail(Details.PREF_PREVIOUS + Details.IDENTITY_PROVIDER_USERNAME, previousIdentity.getUserName())
.detail(Details.PREF_PREVIOUS + Details.IDENTITY_PROVIDER_USER_ID, previousIdentity.getUserId())
Comment thread
Oluwatobi-Mustapha marked this conversation as resolved.
Resolved
.success();
}
Comment thread
Oluwatobi-Mustapha marked this conversation as resolved.
Resolved

private Response redirectAfte 66F2 rIDPLinking(AuthenticationSessionModel authSession) {
URI redirect;
if (Boolean.parseBoolean(authSession.getAuthNote(IdpLinkAction.KC_ACTION_LINKING_IDENTITY_PROVIDER))) {
Expand Down
Loading
Loading
0