From e81107bd8951298fbe607cae1cee2fb8038c698b Mon Sep 17 00:00:00 2001 From: ryan-morris Date: Thu, 17 Sep 2026 09:06:45 -0500 Subject: [PATCH 1/4] Reset phoneNumberVerified when users change their phone number Closes #53019 Signed-off-by: ryan-morris --- .../topics/clients/con-client-scopes.adoc | 2 + .../topics/changes/changes-26_8_0.adoc | 8 + .../userprofile/DefaultUserProfile.java | 37 +++ .../userprofile/UserProfileContext.java | 29 ++- .../tests/account/AccountRestServiceTest.java | 180 +++++++++++++++ .../RequiredActionUpdateProfileTest.java | 57 +++++ .../IdpReviewProfileAuthenticatorTest.java | 213 ++++++++++++++++++ 7 files changed, 516 insertions(+), 10 deletions(-) create mode 100644 tests/base/src/test/java/org/keycloak/tests/broker/IdpReviewProfileAuthenticatorTest.java diff --git a/docs/documentation/server_admin/topics/clients/con-client-scopes.adoc b/docs/documentation/server_admin/topics/clients/con-client-scopes.adoc index 2235dc8e438..3d7b97c3cd1 100644 --- a/docs/documentation/server_admin/topics/clients/con-client-scopes.adoc +++ b/docs/documentation/server_admin/topics/clients/con-client-scopes.adoc @@ -49,6 +49,8 @@ image:images/client-scopes-phone.png[] When the *phone* client scope is linked to a client, the client automatically inherits all the protocol mappers defined in the *phone* client scope. Access tokens issued for this client contain the phone number information about the user, assuming that the user has a defined phone number. +The `phone_number` and `phone_number_verified` claims are mapped from the `phoneNumber` and `phoneNumberVerified` user attributes. {project_name} does not verify phone numbers itself. However, when users change their own `phoneNumber` in the Account Console, through the update profile required action, or when reviewing their profile during their first login through an identity provider, a `phoneNumberVerified` value of `true` is set to `false`, in the same way the email verification status is reset when users change their email. Values written by identity provider mappers or user federation providers are stored as provided. If you add the `phoneNumberVerified` attribute to the user profile, make sure that only administrators can edit it. + Built-in client scopes contain the protocol mappers as defined in the specification. You are free to edit client scopes and create, update, or remove any protocol mappers or role scope mappings. == Consent related settings diff --git a/docs/documentation/upgrading/topics/changes/changes-26_8_0.adoc b/docs/documentation/upgrading/topics/changes/changes-26_8_0.adoc index b4ca774de25..a61a5370f0b 100644 --- a/docs/documentation/upgrading/topics/changes/changes-26_8_0.adoc +++ b/docs/documentation/upgrading/topics/changes/changes-26_8_0.adoc @@ -545,6 +545,14 @@ If you plan to enable this executor, audit the `registeredNodes` map for any aff Re-registering a replacement hostname without first deleting the old entry leaves the old key in the map, which {project_name} continues using for management callbacks regardless of the active policy. +=== `phoneNumberVerified` is reset when users change their phone number + +When a user changes the `phoneNumber` attribute through the account console, the update profile required action, or when reviewing their profile during their first login through an identity provider, {project_name} now sets the `phoneNumberVerified` attribute to `false` if it was `true`, in the same way `emailVerified` is reset when a user changes their email. +These two attributes are the ones mapped to the `phone_number` and `phone_number_verified` claims by the built-in *phone* client scope. + +Changes made by administrators, for example through the Admin REST API, and values written by identity provider mappers do not reset it. +If the `phoneNumberVerified` attribute is declared in the user profile, make sure that only administrators can edit it. + // ------------------------ Deprecated features ------------------------ // == Deprecated features The following sections provide details on deprecated features. diff --git a/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultUserProfile.java b/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultUserProfile.java index 29c196669e7..a3c2bdd28a2 100644 --- a/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultUserProfile.java +++ b/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultUserProfile.java @@ -60,6 +60,10 @@ */ public final class DefaultUserProfile implements UserProfile { + // the attributes mapped to the phone_number and phone_number_verified claims by the built-in "phone" client scope + private static final String PHONE_NUMBER = "phoneNumber"; + private static final String PHONE_NUMBER_VERIFIED = "phoneNumberVerified"; + private final UserProfileMetadata metadata; private final Function userSupplier; private final Attributes attributes; @@ -128,6 +132,8 @@ private UserModel updateInternal(UserModel user, boolean removeAttributes, Attri try { Map> writable = new HashMap<>(attributes.getWritable()); + boolean phoneNumberVerifiedReset = false; + for (Map.Entry> attribute : writable.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList()) { String name = attribute.getKey(); List currentValue = user.getAttributeStream(name) @@ -138,6 +144,10 @@ private UserModel updateInternal(UserModel user, boolean removeAttributes, Attri continue; } + if (PHONE_NUMBER_VERIFIED.equals(name) && phoneNumberVerifiedReset) { + continue; + } + if (isIgnoreAttributeUpdate(removeAttributes, updatedValue, name)) { continue; } @@ -152,6 +162,11 @@ private UserModel updateInternal(UserModel user, boolean removeAttributes, Attri user.setEmailVerified(false); } + if (PHONE_NUMBER.equals(name) && metadata.getContext().isResetPhoneNumberVerified()) { + resetPhoneNumberVerified(user, changeListener); + phoneNumberVerifiedReset = true; + } + for (AttributeChangeListener listener : changeListener) { listener.onChange(name, user, currentValue); } @@ -170,6 +185,10 @@ private UserModel updateInternal(UserModel user, boolean removeAttributes, Attri continue; } + if (PHONE_NUMBER_VERIFIED.equals(name) && phoneNumberVerifiedReset) { + continue; + } + List currentValue = user.getAttributeStream(name).filter(Objects::nonNull).collect(Collectors.toList()); if (isRootAttribute(name)) { @@ -184,6 +203,10 @@ private UserModel updateInternal(UserModel user, boolean removeAttributes, Attri user.removeAttribute(name); } + if (PHONE_NUMBER.equals(name) && metadata.getContext().isResetPhoneNumberVerified()) { + resetPhoneNumberVerified(user, changeListener); + } + for (AttributeChangeListener listener : changeListener) { listener.onChange(name, user, currentValue); } @@ -216,6 +239,20 @@ private boolean isIgnoreAttributeUpdate(boolean removeAttributes, List u return false; } + private void resetPhoneNumberVerified(UserModel user, AttributeChangeListener... changeListener) { + List currentValue = user.getAttributeStream(PHONE_NUMBER_VERIFIED).filter(Objects::nonNull).collect(Collectors.toList()); + + if (currentValue.stream().noneMatch(Boolean::parseBoolean)) { + return; + } + + user.setAttribute(PHONE_NUMBER_VERIFIED, List.of(Boolean.FALSE.toString())); + + for (AttributeChangeListener listener : changeListener) { + listener.onChange(PHONE_NUMBER_VERIFIED, user, currentValue); + } + } + private boolean isCustomAttribute(String name) { return !isRootAttribute(name); } diff --git a/server-spi/src/main/java/org/keycloak/userprofile/UserProfileContext.java b/server-spi/src/main/java/org/keycloak/userprofile/UserProfileContext.java index f6162d0cdd1..07000d7e11b 100644 --- a/server-spi/src/main/java/org/keycloak/userprofile/UserProfileContext.java +++ b/server-spi/src/main/java/org/keycloak/userprofile/UserProfileContext.java @@ -42,53 +42,55 @@ public enum UserProfileContext { /** * In this context, a user profile is managed by themselves during an authentication flow such as when updating the user profile. */ - UPDATE_PROFILE(false, true, true), + UPDATE_PROFILE(false, true, true, true), /** * In this context, a user profile is managed through the management interface such as the Admin API. */ - USER_API(true, false, false), + USER_API(true, false, false, false), /** * In this context, a user profile is managed by themselves through the account console. */ - ACCOUNT(false, true, true), + ACCOUNT(false, true, true, true), /** * In this context, a user profile is managed by themselves when authenticating through a broker. */ - IDP_REVIEW(false, true, false), + IDP_REVIEW(false, true, false, true), /** * In this context, a user profile is managed by themselves when registering to a realm. */ - REGISTRATION(false, true, false), + REGISTRATION(false, true, false, false), /** * In this context, a user profile is managed by themselves when updating their email through an application initiated action. * In this context, only the {@link UserModel#EMAIL} attribute is supported. */ - UPDATE_EMAIL(false, true, true, Set.of(UserModel.EMAIL)::contains), + UPDATE_EMAIL(false, true, true, false, Set.of(UserModel.EMAIL)::contains), /** * In this context, a user profile is managed through the management interface such as the Admin API. */ - SCIM(true, false, false); + SCIM(true, false, false, false); private final boolean resetEmailVerified; + private final boolean resetPhoneNumberVerified; private final Predicate attributeSelector; private final boolean adminContext; private final boolean authFlowContext; - UserProfileContext(boolean adminContext, boolean authFlowContext, boolean resetEmailVerified, Predicate attributeSelector){ + UserProfileContext(boolean adminContext, boolean authFlowContext, boolean resetEmailVerified, boolean resetPhoneNumberVerified, Predicate attributeSelector){ this.adminContext = adminContext; this.authFlowContext = authFlowContext; this.resetEmailVerified = resetEmailVerified; + this.resetPhoneNumberVerified = resetPhoneNumberVerified; this.attributeSelector = attributeSelector; } - UserProfileContext(boolean adminContext, boolean authFlowContext, boolean resetEmailVerified){ - this(adminContext, authFlowContext, resetEmailVerified, StringUtil::isNotBlank); + UserProfileContext(boolean adminContext, boolean authFlowContext, boolean resetEmailVerified, boolean resetPhoneNumberVerified){ + this(adminContext, authFlowContext, resetEmailVerified, resetPhoneNumberVerified, StringUtil::isNotBlank); } /** @@ -112,6 +114,13 @@ public boolean isResetEmailVerified() { return resetEmailVerified; } + /** + * @return true means that the phoneNumberVerified attribute must be reset to false in this context when the phoneNumber attribute is updated + */ + public boolean isResetPhoneNumberVerified() { + return resetPhoneNumberVerified; + } + /** * Check if roles configuration contains role for this context. * diff --git a/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java b/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java index d867a77d3a2..79c89591b4d 100644 --- a/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java @@ -99,6 +99,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.keycloak.testsuite.util.userprofile.UserProfileUtil.PERMISSIONS_ADMIN_EDITABLE; import static org.keycloak.testsuite.util.userprofile.UserProfileUtil.PERMISSIONS_ALL; import static org.hamcrest.CoreMatchers.is; @@ -296,6 +297,185 @@ public void testUpdateProfileEmailChangeSetsEmailVerified() throws IOException { Assertions.assertFalse(user.isEmailVerified()); } + @Test + public void testUpdateProfilePhoneNumberChangeResetsPhoneNumberVerified() throws IOException { + managedRealm.updateWithCleanup(r -> r.registrationEmailAsUsername(false)); + registerUserCleanup("test-user@localhost"); + registerPhoneNumberCleanup("test-user@localhost"); + managedRealm.cleanup().add(r -> UserProfileUtil.setUserProfileConfiguration(r, null)); + setUserProfileConfiguration("{\"attributes\": [" + + "{\"name\": \"email\"," + PERMISSIONS_ALL + "}," + + "{\"name\": \"firstName\"," + PERMISSIONS_ALL + "}," + + "{\"name\": \"lastName\"," + PERMISSIONS_ALL + "}," + + "{\"name\": \"phoneNumber\"," + PERMISSIONS_ALL + "}," + + "{\"name\": \"phoneNumberVerified\"," + PERMISSIONS_ADMIN_EDITABLE + "}" + + "]}"); + + String token = oauth.client("direct-grant", "password").doPasswordGrantRequest("test-user@localhost", "password").getAccessToken(); + UserRepresentation user = getUser(token); + user.setAttributes(Optional.ofNullable(user.getAttributes()).orElse(new HashMap<>())); + + // Setting a number on a user that was never verified does not create the flag + user.getAttributes().put("phoneNumber", List.of("+15555550123")); + user = updateAndGet(user, token); + Assertions.assertEquals(List.of("+15555550123"), user.getAttributes().get("phoneNumber")); + Assertions.assertNull(user.getAttributes().get("phoneNumberVerified")); + + // An administrator asserts verification + UserResource userResource = managedRealm.admin().users().get(user.getId()); + setPhoneNumberVerified(userResource, "+15555550123"); + user = getUser(token); + Assertions.assertEquals(List.of("true"), user.getAttributes().get("phoneNumberVerified")); + + // Same number - flag not reset + user = updateAndGet(user, token); + Assertions.assertEquals(List.of("+15555550123"), user.getAttributes().get("phoneNumber")); + Assertions.assertEquals(List.of("true"), user.getAttributes().get("phoneNumberVerified")); + + // Different number - flag must be reset to false + events.clear(); + user.getAttributes().put("phoneNumber", List.of("+15555550199")); + user = updateAndGet(user, token); + Assertions.assertEquals(List.of("+15555550199"), user.getAttributes().get("phoneNumber")); + Assertions.assertEquals(List.of("false"), user.getAttributes().get("phoneNumberVerified")); + EventAssertion.assertSuccess(events.poll()) + .type(EventType.UPDATE_PROFILE) + .userId(user.getId()) + .details(Details.PREF_PREVIOUS + "phoneNumber", "+15555550123") + .details(Details.PREF_UPDATED + "phoneNumber", "+15555550199") + .details(Details.PREF_PREVIOUS + "phoneNumberVerified", "true") + .details(Details.PREF_UPDATED + "phoneNumberVerified", "false"); + + // Different number with the flag set in another case, as accepted by the boolean claim mapper - flag must be reset to false + org.keycloak.representations.idm.UserRepresentation upperCase = userResource.toRepresentation(); + upperCase.singleAttribute("phoneNumberVerified", "TRUE"); + userResource.update(upperCase); + user = getUser(token); + user.getAttributes().put("phoneNumber", List.of("+15555550198")); + user = updateAndGet(user, token); + Assertions.assertEquals(List.of("false"), user.getAttributes().get("phoneNumberVerified")); + + // Removing the number - flag must be reset to false + setPhoneNumberVerified(userResource, "+15555550123"); + user = getUser(token); + Assertions.assertEquals(List.of("true"), user.getAttributes().get("phoneNumberVerified")); + user.getAttributes().remove("phoneNumber"); + user = updateAndGet(user, token); + Assertions.assertNull(user.getAttributes().get("phoneNumber")); + Assertions.assertEquals(List.of("false"), user.getAttributes().get("phoneNumberVerified")); + + // An administrator changing the number does not reset the flag, as with email + setPhoneNumberVerified(userResource, "+15555550123"); + org.keycloak.representations.idm.UserRepresentation ur = userResource.toRepresentation(); + ur.singleAttribute("phoneNumber", "+15555550100"); + userResource.update(ur); + ur = userResource.toRepresentation(); + Assertions.assertEquals(List.of("+15555550100"), ur.getAttributes().get("phoneNumber")); + Assertions.assertEquals(List.of("true"), ur.getAttributes().get("phoneNumberVerified")); + } + + @Test + public void testUpdateProfilePhoneNumberChangeResetsUserEditablePhoneNumberVerified() throws IOException { + managedRealm.updateWithCleanup(r -> r.registrationEmailAsUsername(false)); + registerUserCleanup("test-user@localhost"); + registerPhoneNumberCleanup("test-user@localhost"); + managedRealm.cleanup().add(r -> UserProfileUtil.setUserProfileConfiguration(r, null)); + setUserProfileConfiguration("{\"attributes\": [" + + "{\"name\": \"email\"," + PERMISSIONS_ALL + "}," + + "{\"name\": \"firstName\"," + PERMISSIONS_ALL + "}," + + "{\"name\": \"lastName\"," + PERMISSIONS_ALL + "}," + + "{\"name\": \"phoneNumber\"," + PERMISSIONS_ALL + "}," + + "{\"name\": \"phoneNumberVerified\"," + PERMISSIONS_ALL + "}" + + "]}"); + + String token = oauth.client("direct-grant", "password").doPasswordGrantRequest("test-user@localhost", "password").getAccessToken(); + UserRepresentation user = getUser(token); + UserResource userResource = managedRealm.admin().users().get(user.getId()); + org.keycloak.representations.idm.UserRepresentation ur = userResource.toRepresentation(); + ur.singleAttribute("phoneNumber", "+15555550123"); + ur.singleAttribute("phoneNumberVerified", "false"); + userResource.update(ur); + + // Setting the flag together with a different number - flag must stay false + events.clear(); + user = getUser(token); + user.getAttributes().put("phoneNumber", List.of("+15555550199")); + user.getAttributes().put("phoneNumberVerified", List.of("true")); + user = updateAndGet(user, token); + Assertions.assertEquals(List.of("+15555550199"), user.getAttributes().get("phoneNumber")); + Assertions.assertEquals(List.of("false"), user.getAttributes().get("phoneNumberVerified")); + EventAssertion.assertSuccess(events.poll()) + .type(EventType.UPDATE_PROFILE) + .userId(user.getId()) + .details(Details.PREF_UPDATED + "phoneNumber", "+15555550199") + .withoutDetails(Details.PREF_PREVIOUS + "phoneNumberVerified", Details.PREF_UPDATED + "phoneNumberVerified"); + + // Keeping the flag set together with a different number - flag must be reset to false + setPhoneNumberVerified(userResource, "+15555550123"); + events.clear(); + user = getUser(token); + user.getAttributes().put("phoneNumber", List.of("+15555550199")); + user.getAttributes().put("phoneNumberVerified", List.of("true")); + user = updateAndGet(user, token); + Assertions.assertEquals(List.of("false"), user.getAttributes().get("phoneNumberVerified")); + EventAssertion.assertSuccess(events.poll()) + .type(EventType.UPDATE_PROFILE) + .userId(user.getId()) + .details(Details.PREF_PREVIOUS + "phoneNumberVerified", "true") + .details(Details.PREF_UPDATED + "phoneNumberVerified", "false"); + } + + @Test + public void testUpdateProfileUnmanagedPhoneNumberChangeResetsPhoneNumberVerified() throws IOException { + managedRealm.updateWithCleanup(r -> r.registrationEmailAsUsername(false)); + registerUserCleanup("test-user@localhost"); + registerPhoneNumberCleanup("test-user@localhost"); + managedRealm.cleanup().add(r -> UserProfileUtil.setUserProfileConfiguration(r, null)); + setUserProfileConfiguration("{\"unmanagedAttributePolicy\": \"ENABLED\", \"attributes\": [" + + "{\"name\": \"email\"," + PERMISSIONS_ALL + "}," + + "{\"name\": \"firstName\"," + PERMISSIONS_ALL + "}," + + "{\"name\": \"lastName\"," + PERMISSIONS_ALL + "}" + + "]}"); + + String token = oauth.client("direct-grant", "password").doPasswordGrantRequest("test-user@localhost", "password").getAccessToken(); + UserRepresentation user = getUser(token); + UserResource userResource = managedRealm.admin().users().get(user.getId()); + setPhoneNumberVerified(userResource, "+15555550123"); + + // Omitting the flag together with a different number - flag must be reset to false, not removed + events.clear(); + user = getUser(token); + user.getAttributes().put("phoneNumber", List.of("+15555550199")); + user.getAttributes().remove("phoneNumberVerified"); + user = updateAndGet(user, token); + Assertions.assertEquals(List.of("+15555550199"), user.getAttributes().get("phoneNumber")); + Assertions.assertEquals(List.of("false"), user.getAttributes().get("phoneNumberVerified")); + EventAssertion.assertSuccess(events.poll()) + .type(EventType.UPDATE_PROFILE) + .userId(user.getId()) + .details(Details.PREF_PREVIOUS + "phoneNumberVerified", "true") + .details(Details.PREF_UPDATED + "phoneNumberVerified", "false"); + } + + private void registerPhoneNumberCleanup(String username) { + // the phone attributes are removed while the user profile configuration of the test is still in place + managedRealm.cleanup().add(r -> { + UserResource userResource = AdminApiUtil.findUserByUsernameId(r, username); + org.keycloak.representations.idm.UserRepresentation ur = userResource.toRepresentation(); + ur.setAttributes(new HashMap<>(Optional.ofNullable(ur.getAttributes()).orElse(Map.of()))); + ur.getAttributes().remove("phoneNumber"); + ur.getAttributes().remove("phoneNumberVerified"); + userResource.update(ur); + }); + } + + private static void setPhoneNumberVerified(UserResource userResource, String phoneNumber) { + org.keycloak.representations.idm.UserRepresentation ur = userResource.toRepresentation(); + ur.singleAttribute("phoneNumber", phoneNumber); + ur.singleAttribute("phoneNumberVerified", "true"); + userResource.update(ur); + } + @Test public void testUpdateProfileEvent() throws IOException { managedRealm.updateWithCleanup(r -> r.registrationEmailAsUsername(false)); diff --git a/tests/base/src/test/java/org/keycloak/tests/actions/RequiredActionUpdateProfileTest.java b/tests/base/src/test/java/org/keycloak/tests/actions/RequiredActionUpdateProfileTest.java index 1f67b0ea78a..9e7cdf64cf5 100644 --- a/tests/base/src/test/java/org/keycloak/tests/actions/RequiredActionUpdateProfileTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/actions/RequiredActionUpdateProfileTest.java @@ -21,6 +21,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -466,6 +467,62 @@ public void updateProfileWithoutRemoveCustomAttributes() { } } + @Test + public void updateProfilePhoneNumberResetsPhoneNumberVerified() { + UserProfileResource upResource = realm.admin().users().userProfile(); + UPConfig upConfig = upResource.getConfiguration(); + UPConfig testUpConfig = upConfig.clone(); + testUpConfig.addOrReplaceAttribute(new UPAttribute("phoneNumber", new UPAttributePermissions(Set.of(ROLE_USER, ROLE_ADMIN), Set.of(ROLE_USER, ROLE_ADMIN)))); + testUpConfig.addOrReplaceAttribute(new UPAttribute("phoneNumberVerified", new UPAttributePermissions(Set.of(ROLE_USER, ROLE_ADMIN), Set.of(ROLE_ADMIN)))); + upResource.update(testUpConfig); + + try { + UserResource user = testUser.admin(); + UserRepresentation userRep = user.toRepresentation(); + userRep.singleAttribute("phoneNumber", "+15555550123"); + userRep.singleAttribute("phoneNumberVerified", "true"); + user.update(userRep); + + oauth.openLoginForm(); + + loginPage.fillLogin("test-user@localhost", PASSWORD); + loginPage.submit(); + + updateProfilePage.assertCurrent(); + updateProfilePage.prepareUpdate().firstName("New first").lastName("New last").otherProfileAttribute(Map.of("phoneNumber", "+15555550199")).submit(); + + Assertions.assertTrue(oauth.parseLoginResponse().isSuccess()); + + EventAssertion.expectRequiredAction(events.poll()).type(EventType.UPDATE_PROFILE).details(Details.CONTEXT, UserProfileContext.UPDATE_PROFILE.name()) + .details(Details.PREF_PREVIOUS + "phoneNumber", "+15555550123").details(Details.PREF_UPDATED + "phoneNumber", "+15555550199") + .details(Details.PREF_PREVIOUS + "phoneNumberVerified", "true").details(Details.PREF_UPDATED + "phoneNumberVerified", "false"); + + EventAssertion.expectLoginSuccess(events.poll()); + + // phone number changed so verify that phoneNumberVerified flag is reset + userRep = user.toRepresentation(); + Assertions.assertEquals(List.of("+15555550199"), userRep.getAttributes().get("phoneNumber")); + Assertions.assertEquals(List.of("false"), userRep.getAttributes().get("phoneNumberVerified")); + + // phone number removed so verify that phoneNumberVerified flag is reset + userRep.singleAttribute("phoneNumberVerified", "true"); + userRep.setRequiredActions(List.of(UserModel.RequiredAction.UPDATE_PROFILE.name())); + user.update(userRep); + + oauth.openLoginForm(); + updateProfilePage.assertCurrent(); + updateProfilePage.prepareUpdate().otherProfileAttribute(Map.of("phoneNumber", "")).submit(); + + Assertions.assertTrue(oauth.parseLoginResponse().isSuccess()); + + userRep = user.toRepresentation(); + Assertions.assertNull(userRep.getAttributes().get("phoneNumber")); + Assertions.assertEquals(List.of("false"), userRep.getAttributes().get("phoneNumberVerified")); + } finally { + upResource.update(upConfig); + } + } + @Test public void testMultivaluedAttributes() { Assumptions.assumeFalse(driver.getBrowserType().equals(BrowserType.HTML_UNIT)); // we can't yet run modern JavaScript using HtmlUnit diff --git a/tests/base/src/test/java/org/keycloak/tests/broker/IdpReviewProfileAuthenticatorTest.java b/tests/base/src/test/java/org/keycloak/tests/broker/IdpReviewProfileAuthenticatorTest.java new file mode 100644 index 00000000000..6da741ac572 --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/broker/IdpReviewProfileAuthenticatorTest.java @@ -0,0 +1,213 @@ +package org.keycloak.tests.broker; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import jakarta.ws.rs.core.Response; + +import org.keycloak.admin.client.resource.UserProfileResource; +import org.keycloak.broker.oidc.OIDCIdentityProviderFactory; +import org.keycloak.broker.provider.HardcodedAttributeMapper; +import org.keycloak.models.IdentityProviderModel; +import org.keycloak.models.utils.DefaultAuthenticationFlows; +import org.keycloak.representations.idm.AuthenticationExecutionInfoRepresentation; +import org.keycloak.representations.idm.AuthenticatorConfigRepresentation; +import org.keycloak.representations.idm.IdentityProviderMapperRepresentation; +import org.keycloak.representations.idm.IdentityProviderRepresentation; +import org.keycloak.representations.idm.UserRepresentation; +import org.keycloak.representations.userprofile.config.UPAttribute; +import org.keycloak.representations.userprofile.config.UPAttributePermissions; +import org.keycloak.representations.userprofile.config.UPConfig; +import org.keycloak.testframework.annotations.InjectRealm; +import org.keycloak.testframework.annotations.KeycloakIntegrationTest; +import org.keycloak.testframework.injection.LifeCycle; +import org.keycloak.testframework.oauth.OAuthClient; +import org.keycloak.testframework.oauth.annotations.InjectOAuthClient; +import org.keycloak.testframework.realm.ClientBuilder; +import org.keycloak.testframework.realm.ManagedRealm; +import org.keycloak.testframework.realm.RealmBuilder; +import org.keycloak.testframework.realm.RealmConfig; +import org.keycloak.testframework.realm.UserBuilder; +import org.keycloak.testframework.ui.annotations.InjectPage; +import org.keycloak.testframework.ui.page.IdpReviewUserProfilePage; +import org.keycloak.testframework.ui.page.LoginPage; +import org.keycloak.testframework.util.ApiUtil; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.keycloak.userprofile.config.UPConfigUtils.ROLE_ADMIN; +import static org.keycloak.userprofile.config.UPConfigUtils.ROLE_USER; + +/** + * Integration tests for {@link org.keycloak.authentication.authenticators.broker.IdpReviewProfileAuthenticator}. + */ +@KeycloakIntegrationTest +public class IdpReviewProfileAuthenticatorTest { + + private static final String IDP_ALIAS = "review-profile-idp"; + private static final String CLIENT_ID = "broker-client"; + private static final String CLIENT_SECRET = "broker-secret"; + private static final String PROVIDER_USERNAME = "provider-user"; + + @InjectRealm(ref = "provider", config = ProviderRealmConfig.class, lifecycle = LifeCycle.CLASS) + ManagedRealm providerRealm; + + @InjectRealm(ref = "consumer", config = ConsumerRealmConfig.class, lifecycle = LifeCycle.CLASS) + ManagedRealm consumerRealm; + + @InjectOAuthClient(realmRef = "consumer") + OAuthClient oauth; + + @InjectPage + LoginPage loginPage; + + @InjectPage + IdpReviewUserProfilePage reviewProfilePage; + + @BeforeEach + public void setup() { + UserProfileResource upResource = consumerRealm.admin().users().userProfile(); + UPConfig upConfig = upResource.getConfiguration(); + UPConfig testUpConfig = upConfig.clone(); + testUpConfig.addOrReplaceAttribute(new UPAttribute("phoneNumber", new UPAttributePermissions(Set.of(ROLE_USER, ROLE_ADMIN), Set.of(ROLE_USER, ROLE_ADMIN)))); + testUpConfig.addOrReplaceAttribute(new UPAttribute("phoneNumberVerified", new UPAttributePermissions(Set.of(ROLE_USER, ROLE_ADMIN), Set.of(ROLE_ADMIN)))); + upResource.update(testUpConfig); + consumerRealm.cleanup().add(r -> r.users().userProfile().update(upConfig)); + + setUpdateProfileOnFirstLogin(IdentityProviderRepresentation.UPFLM_ON); + addHardcodedAttributeMapper("phone-number-mapper", "phoneNumber", "+15555550123"); + addHardcodedAttributeMapper("phone-number-verified-mapper", "phoneNumberVerified", "true"); + createProviderUser(); + } + + @Test + public void testReviewProfilePhoneNumberChangeResetsPhoneNumberVerified() { + loginThroughIdp(); + + reviewProfilePage.assertCurrent(); + reviewProfilePage.prepareUpdate().otherProfileAttribute(Map.of("phoneNumber", "+15555550199")).submit(); + + Assertions.assertTrue(oauth.parseLoginResponse().isSuccess()); + + UserRepresentation user = getConsumerUser(); + Assertions.assertEquals(List.of("+15555550199"), user.getAttributes().get("phoneNumber")); + Assertions.assertEquals(List.of("false"), user.getAttributes().get("phoneNumberVerified")); + } + + @Test + public void testReviewProfilePhoneNumberUnchangedKeepsPhoneNumberVerified() { + loginThroughIdp(); + + reviewProfilePage.assertCurrent(); + reviewProfilePage.prepareUpdate().submit(); + + Assertions.assertTrue(oauth.parseLoginResponse().isSuccess()); + + UserRepresentation user = getConsumerUser(); + Assertions.assertEquals(List.of("+15555550123"), user.getAttributes().get("phoneNumber")); + Assertions.assertEquals(List.of("true"), user.getAttributes().get("phoneNumberVerified")); + } + + private void loginThroughIdp() { + oauth.openLoginForm(); + loginPage.clickSocial(IDP_ALIAS); + loginPage.fillLogin(PROVIDER_USERNAME, "password"); + loginPage.submit(); + } + + private UserRepresentation getConsumerUser() { + List users = consumerRealm.admin().users().search(PROVIDER_USERNAME, true); + Assertions.assertEquals(1, users.size()); + String userId = users.get(0).getId(); + consumerRealm.cleanup().add(r -> r.users().get(userId).remove()); + return consumerRealm.admin().users().get(userId).toRepresentation(); + } + + private void setUpdateProfileOnFirstLogin(String mode) { + var flows = consumerRealm.admin().flows(); + for (AuthenticationExecutionInfoRepresentation execution : flows.getExecutions(DefaultAuthenticationFlows.FIRST_BROKER_LOGIN_FLOW)) { + if (DefaultAuthenticationFlows.IDP_REVIEW_PROFILE_CONFIG_ALIAS.equals(execution.getAlias())) { + AuthenticatorConfigRepresentation config = flows.getAuthenticatorConfig(execution.getAuthenticationConfig()); + String previousMode = config.getConfig().get("update.profile.on.first.login"); + config.getConfig().put("update.profile.on.first.login", mode); + flows.updateAuthenticatorConfig(config.getId(), config); + consumerRealm.cleanup().add(r -> { + config.getConfig().put("update.profile.on.first.login", previousMode); + r.flows().updateAuthenticatorConfig(config.getId(), config); + }); + } + } + } + + private void addHardcodedAttributeMapper(String mapperName, String attribute, String value) { + IdentityProviderMapperRepresentation mapper = new IdentityProviderMapperRepresentation(); + mapper.setName(mapperName); + mapper.setIdentityProviderAlias(IDP_ALIAS); + mapper.setIdentityProviderMapper(HardcodedAttributeMapper.PROVIDER_ID); + mapper.setConfig(Map.of( + HardcodedAttributeMapper.ATTRIBUTE, attribute, + HardcodedAttributeMapper.ATTRIBUTE_VALUE, value + )); + try (Response response = consumerRealm.admin().identityProviders().get(IDP_ALIAS).addMapper(mapper)) { + Assertions.assertEquals(201, response.getStatus()); + String mapperId = ApiUtil.getCreatedId(response); + consumerRealm.cleanup().add(r -> r.identityProviders().get(IDP_ALIAS).delete(mapperId)); + } + } + + private void createProviderUser() { + UserRepresentation user = UserBuilder.create(PROVIDER_USERNAME) + .password("password") + .email(PROVIDER_USERNAME + "@example.com") + .emailVerified(true) + .firstName("Provider") + .lastName("User") + .build(); + try (Response response = providerRealm.admin().users().create(user)) { + Assertions.assertEquals(201, response.getStatus()); + String userId = ApiUtil.getCreatedId(response); + providerRealm.cleanup().add(r -> r.users().get(userId).remove()); + } + } + + public static class ProviderRealmConfig implements RealmConfig { + + @Override + public RealmBuilder configure(RealmBuilder realm) { + return realm.clients( + ClientBuilder.create(CLIENT_ID) + .secret(CLIENT_SECRET) + .redirectUris("*") + .directAccessGrantsEnabled() + ); + } + } + + public static class ConsumerRealmConfig implements RealmConfig { + + @Override + public RealmBuilder configure(RealmBuilder realm) { + String providerBase = "http://localhost:8080/realms/provider"; + + IdentityProviderRepresentation idp = new IdentityProviderRepresentation(); + idp.setAlias(IDP_ALIAS); + idp.setProviderId(OIDCIdentityProviderFactory.PROVIDER_ID); + idp.setEnabled(true); + idp.setTrustEmail(true); + idp.setConfig(Map.of( + "clientId", CLIENT_ID, + "clientSecret", CLIENT_SECRET, + "authorizationUrl", providerBase + "/protocol/openid-connect/auth", + "tokenUrl", providerBase + "/protocol/openid-connect/token", + "userInfoUrl", providerBase + "/protocol/openid-connect/userinfo", + "jwksUrl", providerBase + "/protocol/openid-connect/certs", + "defaultScope", "openid email profile", + IdentityProviderModel.SYNC_MODE, "IMPORT" + )); + return realm.identityProviders(idp); + } + } +} From 37c4dd2e498bef5978ac26fca9e8785663daa22c Mon Sep 17 00:00:00 2001 From: ryan-morris Date: Mon, 21 Sep 2026 09:57:51 -0500 Subject: [PATCH 2/4] Keep phoneNumberVerified when the phone number is removed When an update removes both phoneNumber and phoneNumberVerified, the flag is reset to false rather than removed. Signed-off-by: ryan-morris --- .../org/keycloak/userprofile/DefaultUserProfile.java | 12 ++++++++---- .../tests/account/AccountRestServiceTest.java | 9 +++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultUserProfile.java b/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultUserProfile.java index a3c2bdd28a2..e6bad8eb6c9 100644 --- a/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultUserProfile.java +++ b/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultUserProfile.java @@ -180,15 +180,19 @@ private UserModel updateInternal(UserModel user, boolean removeAttributes, Attri attrsToRemove.removeAll(attributes.nameSet()); + boolean phoneNumberRemoved = attrsToRemove.contains(PHONE_NUMBER) && !attributes.isReadOnly(PHONE_NUMBER) + && metadata.getContext().isResetPhoneNumberVerified(); + + if (phoneNumberVerifiedReset || phoneNumberRemoved) { + // reset rather than removed + attrsToRemove.remove(PHONE_NUMBER_VERIFIED); + } + for (String name : attrsToRemove) { if (attributes.isReadOnly(name)) { continue; } - if (PHONE_NUMBER_VERIFIED.equals(name) && phoneNumberVerifiedReset) { - continue; - } - List currentValue = user.getAttributeStream(name).filter(Objects::nonNull).collect(Collectors.toList()); if (isRootAttribute(name)) { diff --git a/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java b/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java index 79c89591b4d..4c06b4c70f7 100644 --- a/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java @@ -455,6 +455,15 @@ public void testUpdateProfileUnmanagedPhoneNumberChangeResetsPhoneNumberVerified .userId(user.getId()) .details(Details.PREF_PREVIOUS + "phoneNumberVerified", "true") .details(Details.PREF_UPDATED + "phoneNumberVerified", "false"); + + // Omitting both the number and the flag - flag must be reset to false, not removed + setPhoneNumberVerified(userResource, "+15555550123"); + user = getUser(token); + user.getAttributes().remove("phoneNumber"); + user.getAttributes().remove("phoneNumberVerified"); + user = updateAndGet(user, token); + Assertions.assertNull(user.getAttributes().get("phoneNumber")); + Assertions.assertEquals(List.of("false"), user.getAttributes().get("phoneNumberVerified")); } private void registerPhoneNumberCleanup(String username) { From 96cc65efdf27e425be9304483bc9a5402bfc40df Mon Sep 17 00:00:00 2001 From: ryan-morris Date: Tue, 29 Sep 2026 11:26:35 -0500 Subject: [PATCH 3/4] Remove the upgrading note for the phoneNumberVerified reset Signed-off-by: ryan-morris --- .../upgrading/topics/changes/changes-26_8_0.adoc | 8 -------- 1 file changed, 8 deletions(-) diff --git a/docs/documentation/upgrading/topics/changes/changes-26_8_0.adoc b/docs/documentation/upgrading/topics/changes/changes-26_8_0.adoc index a61a5370f0b..b4ca774de25 100644 --- a/docs/documentation/upgrading/topics/changes/changes-26_8_0.adoc +++ b/docs/documentation/upgrading/topics/changes/changes-26_8_0.adoc @@ -545,14 +545,6 @@ If you plan to enable this executor, audit the `registeredNodes` map for any aff Re-registering a replacement hostname without first deleting the old entry leaves the old key in the map, which {project_name} continues using for management callbacks regardless of the active policy. -=== `phoneNumberVerified` is reset when users change their phone number - -When a user changes the `phoneNumber` attribute through the account console, the update profile required action, or when reviewing their profile during their first login through an identity provider, {project_name} now sets the `phoneNumberVerified` attribute to `false` if it was `true`, in the same way `emailVerified` is reset when a user changes their email. -These two attributes are the ones mapped to the `phone_number` and `phone_number_verified` claims by the built-in *phone* client scope. - -Changes made by administrators, for example through the Admin REST API, and values written by identity provider mappers do not reset it. -If the `phoneNumberVerified` attribute is declared in the user profile, make sure that only administrators can edit it. - // ------------------------ Deprecated features ------------------------ // == Deprecated features The following sections provide details on deprecated features. From 74d05346fefae36369f2165466c485af76324b90 Mon Sep 17 00:00:00 2001 From: ryan-morris Date: Mon, 26 Oct 2026 14:43:50 -0500 Subject: [PATCH 4/4] Do not write a submitted phoneNumberVerified when the number is being removed With unmanaged attributes enabled, an update that omits phoneNumber but submits phoneNumberVerified first wrote the submitted flag and then reset it, so the UPDATE_PROFILE event reported a verification change that never happened. The broker tests now take the provider endpoints from the provider realm's base URL, so they also run when the server uses TLS. Signed-off-by: ryan-morris --- .../userprofile/DefaultUserProfile.java | 9 +++++---- .../tests/account/AccountRestServiceTest.java | 19 +++++++++++++++++++ .../IdpReviewProfileAuthenticatorTest.java | 15 +++++++++++++++ 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultUserProfile.java b/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultUserProfile.java index e6bad8eb6c9..36871e360f6 100644 --- a/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultUserProfile.java +++ b/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultUserProfile.java @@ -133,6 +133,10 @@ private UserModel updateInternal(UserModel user, boolean removeAttributes, Attri Map> writable = new HashMap<>(attributes.getWritable()); boolean phoneNumberVerifiedReset = false; + // the number is removed below, which resets the flag, so a submitted flag must not be written first + boolean phoneNumberRemoved = removeAttributes && metadata.getContext().isResetPhoneNumberVerified() + && user.getAttributes().containsKey(PHONE_NUMBER) && !attributes.nameSet().contains(PHONE_NUMBER) + && !attributes.isReadOnly(PHONE_NUMBER); for (Map.Entry> attribute : writable.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList()) { String name = attribute.getKey(); @@ -144,7 +148,7 @@ private UserModel updateInternal(UserModel user, boolean removeAttributes, Attri continue; } - if (PHONE_NUMBER_VERIFIED.equals(name) && phoneNumberVerifiedReset) { + if (PHONE_NUMBER_VERIFIED.equals(name) && (phoneNumberVerifiedReset || phoneNumberRemoved)) { continue; } @@ -180,9 +184,6 @@ private UserModel updateInternal(UserModel user, boolean removeAttributes, Attri attrsToRemove.removeAll(attributes.nameSet()); - boolean phoneNumberRemoved = attrsToRemove.contains(PHONE_NUMBER) && !attributes.isReadOnly(PHONE_NUMBER) - && metadata.getContext().isResetPhoneNumberVerified(); - if (phoneNumberVerifiedReset || phoneNumberRemoved) { // reset rather than removed attrsToRemove.remove(PHONE_NUMBER_VERIFIED); diff --git a/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java b/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java index 4c06b4c70f7..58f87f8389f 100644 --- a/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/account/AccountRestServiceTest.java @@ -464,6 +464,25 @@ public void testUpdateProfileUnmanagedPhoneNumberChangeResetsPhoneNumberVerified user = updateAndGet(user, token); Assertions.assertNull(user.getAttributes().get("phoneNumber")); Assertions.assertEquals(List.of("false"), user.getAttributes().get("phoneNumberVerified")); + + // Omitting the number while submitting the flag as true - the flag must stay false and not show up in the event + org.keycloak.representations.idm.UserRepresentation ur = userResource.toRepresentation(); + ur.singleAttribute("phoneNumber", "+15555550123"); + ur.singleAttribute("phoneNumberVerified", "false"); + userResource.update(ur); + events.clear(); + user = getUser(token); + user.getAttributes().remove("phoneNumber"); + user.getAttributes().put("phoneNumberVerified", List.of("true")); + user = updateAndGet(user, token); + Assertions.assertNull(user.getAttributes().get("phoneNumber")); + Assertions.assertEquals(List.of("false"), user.getAttributes().get("phoneNumberVerified")); + EventRepresentation event = events.poll(); + EventAssertion.assertSuccess(event) + .type(EventType.UPDATE_PROFILE) + .userId(user.getId()); + Assertions.assertFalse(event.getDetails().containsKey(Details.PREF_PREVIOUS + "phoneNumberVerified")); + Assertions.assertFalse(event.getDetails().containsKey(Details.PREF_UPDATED + "phoneNumberVerified")); } private void registerPhoneNumberCleanup(String username) { diff --git a/tests/base/src/test/java/org/keycloak/tests/broker/IdpReviewProfileAuthenticatorTest.java b/tests/base/src/test/java/org/keycloak/tests/broker/IdpReviewProfileAuthenticatorTest.java index 6da741ac572..3e52e5b2076 100644 --- a/tests/base/src/test/java/org/keycloak/tests/broker/IdpReviewProfileAuthenticatorTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/broker/IdpReviewProfileAuthenticatorTest.java @@ -77,6 +77,7 @@ public void setup() { upResource.update(testUpConfig); consumerRealm.cleanup().add(r -> r.users().userProfile().update(upConfig)); + configureBrokerEndpoints(); setUpdateProfileOnFirstLogin(IdentityProviderRepresentation.UPFLM_ON); addHardcodedAttributeMapper("phone-number-mapper", "phoneNumber", "+15555550123"); addHardcodedAttributeMapper("phone-number-verified-mapper", "phoneNumberVerified", "true"); @@ -126,6 +127,20 @@ private UserRepresentation getConsumerUser() { return consumerRealm.admin().users().get(userId).toRepresentation(); } + private void configureBrokerEndpoints() { + // the realm config only has placeholders, the server may run on another scheme or port + String providerBaseUrl = providerRealm.getBaseUrl(); + IdentityProviderRepresentation idp = consumerRealm.admin().identityProviders().get(IDP_ALIAS).toRepresentation(); + Map config = idp.getConfig(); + config.put("authorizationUrl", providerBaseUrl + "/protocol/openid-connect/auth"); + config.put("tokenUrl", providerBaseUrl + "/protocol/openid-connect/token"); + config.put("userInfoUrl", providerBaseUrl + "/protocol/openid-connect/userinfo"); + config.put("jwksUrl", providerBaseUrl + "/protocol/openid-connect/certs"); + // the admin API masks the secret, and rejects a changed token URL without the real one + config.put("clientSecret", CLIENT_SECRET); + consumerRealm.admin().identityProviders().get(IDP_ALIAS).update(idp); + } + private void setUpdateProfileOnFirstLogin(String mode) { var flows = consumerRealm.admin().flows(); for (AuthenticationExecutionInfoRepresentation execution : flows.getExecutions(DefaultAuthenticationFlows.FIRST_BROKER_LOGIN_FLOW)) {