8000 KEYCLOAK-17851 change emailVerified User field with UserAttributeMappers (conditional trust email) by cgeorgilakis · Pull Request #8018 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ public void setSingleAttribute(String name, String value) {
} else if (UserModel.USERNAME.equals(name)) {
setUsername(value);
return;
} else if (UserModel.EMAIL_VERIFIED.equals(name)) {
setEmailVerified(Boolean.valueOf(value));
return;
}
// Remove all existing
if (value == null) {
Expand Down Expand Up @@ -172,6 +175,9 @@ public void setAttribute(String name, List<String> values) {
} else if (UserModel.USERNAME.equals(name)) {
setUsername(valueToSet);
return;
} else if (UserModel.EMAIL_VERIFIED.equals(name)) {
setEmailVerified(Boolean.valueOf(valueToSet));
return;
}
// Remove all existing
removeAttribute(name);
Expand Down Expand Up @@ -224,6 +230,8 @@ public String getFirstAttribute(String name) {
return user.getEmail();
} else if (UserModel.USERNAME.equals(name)) {
return user.getUsername();
} else if (UserModel.EMAIL_VERIFIED.equals(name)) {
return String.valueOf(user.isEmailVerified());
}
for (UserAttributeEntity attr : user.getAttributes()) {
if (attr.getName().equals(name)) {
Expand All @@ -243,6 +251,8 @@ public Stream<String> getAttributeStream(String name) {
return Stream.of(user.getEmail());
} else if (UserModel.USERNAME.equals(name)) {
return Stream.of(user.getUsername());
} else if (UserModel.EMAIL_VERIFIED.equals(name)) {
return Stream.of(String.valueOf(user.isEmailVerified()));
}
return user.getAttributes().stream().filter(attribute -> Objects.equals(attribute.getName(), name)).
map(attribute -> attribute.getValue());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ private Optional<String> getSpecialAttributeValue(String name) {
return Optional.ofNullable(entity.getEmail());
} else if (UserModel.USERNAME.equals(name)) {
return Optional.ofNullable(entity.getUsername());
} else if (UserModel.EMAIL_VERIFIED.equals(name)) {
return Optional.ofNullable(String.valueOf(entity.isEmailVerified()));
}

return Optional.empty();
Expand All @@ -113,6 +115,9 @@ private boolean setSpecialAttributeValue(String name, String value) {
} else if (UserModel.USERNAME.equals(name)) {
setUsername(value);
return true;
}else if (UserModel.EMAIL_VERIFIED.equals(name)) {
setEmailVerified(Boolean.valueOf(value));
return true;
}

return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public class BrokeredIdentityContext {
private String username;
private String modelUsername;
private String email;
private boolean emailVerified;
private String firstName;
private String lastName;
private String brokerSessionId;
Expand Down Expand Up @@ -113,6 +114,14 @@ public void setEmail(String email) {
this.email = email;
}

public boolean isEmailVerified() {
return emailVerified;
}

public void setEmailVerified(boolean emailVerified) {
this.emailVerified = emailVerified;
}

public String getBrokerSessionId() {
return brokerSessionId;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@ public void setEmail(String email) {
setSingleAttribute(UserModel.EMAIL, email);
}

@Override
public Boolean isEmailVerified() {
return Boolean.valueOf(getFirstAttribute(UserModel.EMAIL_VERIFIED));
}

@Override
public void setEmailVerified(Boolean emailVerified) {
setSingleAttribute(UserModel.EMAIL_VERIFIED, emailVerified.toString());
}

@Override
public String getFirstName() {
return getFirstAttribute(UserModel.FIRST_NAME);
Expand Down Expand Up @@ -269,6 +279,7 @@ public BrokeredIdentityContext deserialize(KeycloakSession session, Authenticati
ctx.setUsername(getBrokerUsername());
ctx.setModelUsername(getModelUsername());
ctx.setEmail(getEmail());
ctx.setEmailVerified(isEmailVerified());
ctx.setFirstName(getFirstName());
ctx.setLastName(getLastName());
ctx.setBrokerSessionId(getBrokerSessionId());
Expand Down Expand Up @@ -309,6 +320,7 @@ public static SerializedBrokeredIdentityContext serialize(BrokeredIdentityContex
ctx.setBrokerUsername(context.getUsername());
ctx.setModelUsername(context.getModelUsername());
ctx.setEmail(context.getEmail());
ctx.setEmailVerified(context.isEmailVerified());
ctx.setFirstName(context.getFirstName());
ctx.setLastName(context.getLastName());
ctx.setBrokerSessionId(context.getBrokerSessionId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ public interface UpdateProfileContext {

void setEmail(String email);

Boolean isEmailVerified();

void setEmailVerified(Boolean emailVerified);

String getFirstName();

void setFirstName(String firstName);
Expand Down
Original file line number Diff line number Diff line change
10000 Expand Up @@ -73,6 +73,16 @@ public void setEmail(String email) {
user.setEmail(email);
}

@Override
public Boolean isEmailVerified() {
return user.isEmailVerified();
}

@Override
public void setEmailVerified(Boolean emailVerified) {
user.setEmailVerified(emailVerified);
}

@Override
public String getFirstName() {
return user.getFirstName();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public abstract class AbstractJsonUserAttributeMapper extends AbstractIdentityPr
* Key in {@link BrokeredIdentityContext#getContextData()} where {@link JsonNode} with user profile is stored.
*/
public static final String CONTEXT_JSON_NODE = OIDCIdentityProvider.USER_INFO;
public static final String EMAIL_VERIFIED = "emailVerified";

private static final List<ProviderConfigProperty> configProperties = new ArrayList<ProviderConfigProperty>();

Expand Down Expand Up @@ -136,7 +137,9 @@ public void preprocessFederatedIdentity(KeycloakSession session, RealmModel real

Object value = getJsonValue(mapperModel, context);
if (value != null) {
if (value instanceof List) {
if (EMAIL_VERIFIED.equalsIgnoreCase(attribute)) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure why there is a need for special handling of "emailVerified" attribute on this particular place? As I can see that none of other "special" attributes" (username, email, firstName, lastname) is handled here in this class.

IMO it will be better to make sure that all the places in the model classes like org.keycloak.models.jpa.UserAdapter and org.keycloak.models.map.user.MapUserAdapter are updated to make sure that:
user.setAttribute("emailVerified", "true") works as expected and calls setEmailVerified internally inside the UserAdapter itself. Similarly will be good if all other methods like user.setSingleAttribute, user.getAttribute, user.getFirstAttribute are updated to properly handle "emailVerified" attribute and delegate to the particular "setEmailVerified" or "getEmailVerified" property internally. I see you updated just single place in these classes, but not all places where other special attributes are handled.

In other words, will be good to handle emailVerified in the same places in the codebase when all other mess related to other "special attributes" (username, email, firstName, lastname) is handled. But will be good to avoid introduce more mess to other places :-)

I guess that if you properly update model classes, there won't be even need to update any brokering stuff at all (not even introduce BrokeredIdentityContext.setEmailVerified() and BrokeredIdentityContext.getEmailVerified() methods. As calling of user.setAttribute("emailVerified", "true") will be effectively same as user.setEmailVerified(true) and similarly for getters. But maybe I am too optimistic here :-)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This if is needed here. See my general comment.

context.setEmailVerified(Boolean.valueOf(value.toString()));
} else if (value instanceof List) {
context.setUserAttribute(attribute, (List<String>) value);
} else {
context.setUserAttribute(attribute, value.toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public class UserAttributeMapper extends AbstractClaimMapper {

public static final String USER_ATTRIBUTE = "user.attribute";
public static final String EMAIL = "email";
public static final String EMAIL_VERIFIED = "emailVerified";
public static final String FIRST_NAME = "firstName";
public static final String LAST_NAME = "lastName";
private static final Set<IdentityProviderSyncMode> IDENTITY_PROVIDER_SYNC_MODES = new HashSet<>(Arrays.asList(IdentityProviderSyncMode.values()));
Expand Down Expand Up @@ -111,21 +112,26 @@ public void preprocessFederatedIdentity(KeycloakSession session, RealmModel real
return;
}
Object value = getClaimValue(mapperModel, context);
List<String> values = toList(value);

if (EMAIL.equalsIgnoreCase(attribute)) {
setIfNotEmpty(context::setEmail, values);
} else if (FIRST_NAME.equalsIgnoreCase(attribute)) {
setIfNotEmpty(context::setFirstName, values);
} else if (LAST_NAME.equalsIgnoreCase(attribute)) {
setIfNotEmpty(context::setLastName, values);
if (EMAIL_VERIFIED.equalsIgnoreCase(attribute)) {
boolean verified = value == null ? false : Boolean.valueOf(value.toString());
context.setEmailVerified(verified);
} else {
List<String> valuesToString = values.stream()
.filter(Objects::nonNull)
.map(Object::toString)
.collect(Collectors.toList());

context.setUserAttribute(attribute, valuesToString);
List<String> values = toList(value);

if (EMAIL.equalsIgnoreCase(attribute)) {
setIfNotEmpty(context::setEmail, values);
} else if (FIRST_NAME.equalsIgnoreCase(attribute)) {
setIfNotEmpty(context::setFirstName, values);
} else if (LAST_NAME.equalsIgnoreCase(attribute)) {
setIfNotEmpty(context::setLastName, values);
} else {
List<String> valuesToString = values.stream()
.filter(Objects::nonNull)
.map(Object::toString)
.collect(Collectors.toList());

context.setUserAttribute(attribute, valuesToString);
}
}
}

Expand Down Expand Up @@ -159,6 +165,9 @@ public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserMo
setIfNotEmpty(user::setFirstName, values);
} else if (LAST_NAME.equalsIgnoreCase(attribute)) {
setIfNotEmpty(user::setLastName, values);
} else if (EMAIL_VERIFIED.equalsIgnoreCase(attribute)) {
if (values != null && ! values.isEmpty())
user.setEmailVerified(Boolean.valueOf(values.get(0)));
} else {
List<String> current = user.getAttributeStream(attribute).collect(Collectors.toList());
if (!CollectionUtil.collectionEquals(values, current)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ public class UserAttributeMapper extends AbstractIdentityProviderMapper implemen
public static final String ATTRIBUTE_NAME_FORMAT = "attribute.name.format";
public static final String USER_ATTRIBUTE = "user.attribute";
private static final String EMAIL = "email";
private static final String EMAIL_ATTRIBUTE = "urn:oid:0.9.2342.19200300.100.1.3";
public static final String EMAIL_VERIFIED = "emailVerified";
private static final String FIRST_NAME = "firstName";
private static final String LAST_NAME = "lastName";
private static final Set<IdentityProviderSyncMode> IDENTITY_PROVIDER_SYNC_MODES = new HashSet<>(Arrays.asList(IdentityProviderSyncMode.values()));
Expand Down Expand Up @@ -149,6 +151,12 @@ public void preprocessFederatedIdentity(KeycloakSession session, RealmModel real
setIfNotEmpty(context::setFirstName, attributeValuesInContext);
} else if (attribute.equalsIgnoreCase(LAST_NAME)) {
setIfNotEmpty(context::setLastName, attributeValuesInContext);
} else if (attribute.equalsIgnoreCase(EMAIL_VERIFIED)) {
//SAML release list of verified email
//check if email consists in email verified list
List<String> emailAttribute = findAttributeValuesInContext(EMAIL_ATTRIBUTE, context);
Boolean verified = attributeValuesInContext!= null && emailAttribute != null && ! emailAttribute.isEmpty() && attributeValuesInContext.contains(emailAttribute.get(0));
context.setEmailVerified(verified);
} else {
context.setUserAttribute(attribute, attributeValuesInContext);
}
Expand Down Expand Up @@ -210,7 +218,15 @@ public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserMo
setIfNotEmptyAndDifferent(user::setFirstName, user::getFirstName, attributeValuesInContext);
} else if (attribute.equalsIgnoreCase(LAST_NAME)) {
setIfNotEmptyAndDifferent(user::setLastName, user::getLastName, attributeValuesInContext);
} else {
} else if (EMAIL_VERIFIED.equalsIgnoreCase(attribute)) {
//SAML release list of verified email
//check if email released by SAML IdP consists in email verified list and is user email
List<String> emailAttribute = findAttributeValuesInContext(EMAIL_ATTRIBUTE, context);
if (emailAttribute != null && !emailAttribute.isEmpty() && user.getEmail().equals(emailAttribute.get(0))) {
Boolean verified = attributeValuesInContext != null && attributeValuesInContext.contains(user.getEmail());
user.setEmailVerified(verified);
}
}else {
List<String> currentAttributeValues = user.getAttributes().get(attribute);
if (attributeValuesInContext == null) {
// attribute no longer sent by brokered idp, remove it
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public abstract class AbstractUserAttributeMapperTest extends AbstractIdentityPr
protected static final String MAPPED_ATTRIBUTE_NAME = "mapped-user-attribute";
protected static final String MAPPED_ATTRIBUTE_FRIENDLY_NAME = "mapped-user-attribute-friendly";

private static final Set<String> PROTECTED_NAMES = ImmutableSet.<String>builder().add("email").add("lastName").add("firstName").build();
private static final Set<String> PROTECTED_NAMES = ImmutableSet.<String>builder().add("email").add("lastName").add("firstName").add("emailVerified").build();
private static final Map<String, String> ATTRIBUTE_NAME_TRANSLATION = ImmutableMap.<String, String>builder()
.put("dotted.email", "dotted.email")
.put("nested.email", "nested.email")
Expand Down Expand Up @@ -83,14 +83,17 @@ private void assertUserAttributes(Map<String, List<String>> attrs, UserRepresent
if (attrs.containsKey("lastName")) {
assertThat(userRep.getLastName(), equalTo(attrs.get("lastName").get(0)));
}
if (attrs.containsKey("emailVerified")) {
assertThat(userRep.isEmailVerified(), equalTo(Boolean.valueOf(attrs.get("emailVerified").get(0))));
}
}

private void testValueMappingForImportSyncMode(Map<String, List<String>> initialUserAttributes, Map<String, List<String>> modifiedUserAttributes) {
protected void testValueMappingForImportSyncMode(Map<String, List<String>> initialUserAttributes, Map<String, List<String>> modifiedUserAttributes) {
addIdentityProviderToConsumerRealm(IdentityProviderMapperSyncMode.IMPORT);
testValueMapping(initialUserAttributes, modifiedUserAttributes, initialUserAttributes);
}

private void testValueMappingForForceSyncMode(Map<String, List<String>> initialUserAttributes, Map<String, List<String>> modifiedUserAttributes) {
protected void testValueMappingForForceSyncMode(Map<String, List<String>> initialUserAttributes, Map<String, List<String>> modifiedUserAttributes) {
addIdentityProviderToConsumerRealm(IdentityProviderMapperSyncMode.FORCE);
testValueMapping(initialUserAttributes, modifiedUserAttributes, modifiedUserAttributes);
}
Expand Down Expand Up @@ -128,6 +131,9 @@ private void testValueMapping(Map<String, List<String>> initialUserAttributes, M
if (modifiedUserAttributes.containsKey("lastName")) {
userRepProvider.setLastName(modifiedUserAttributes.get("lastName").get(0));
}
if (modifiedUserAttributes.containsKey("emailVerified")) {
userRepProvider.setEmailVerified(Boolean.valueOf(modifiedUserAttributes.get("emailVerified").get(0)));
}
adminClient.realm(bc.providerRealmName()).users().get(userRepProvider.getId()).update(userRepProvider);

logInAsUserInIDP();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package org.keycloak.testsuite.broker;

import java.util.List;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import org.keycloak.broker.oidc.mappers.UserAttributeMapper;
import org.keycloak.models.IdentityProviderMapperModel;
import org.keycloak.models.IdentityProviderMapperSyncMode;
Expand Down Expand Up @@ -53,7 +56,38 @@ protected Iterable<IdentityProviderMapperRepresentation> createIdentityProviderM
.put(UserAttributeMapper.USER_ATTRIBUTE, "dotted.email")
.build());

return Lists.newArrayList(attrMapper1, emailAttrMapper, nestedEmailAttrMapper, dottedEmailAttrMapper);
IdentityProviderMapperRepresentation emailVerifiedAttrMapper = new IdentityProviderMapperRepresentation();
emailVerifiedAttrMapper.setName("emailVerified");
emailVerifiedAttrMapper.setIdentityProviderMapper(UserAttributeMapper.PROVIDER_ID);
emailVerifiedAttrMapper.setConfig(ImmutableMap.<String,String>builder()
.put(IdentityProviderMapperModel.SYNC_MODE, syncMode.toString())
7D4E .put(UserAttributeMapper.CLAIM, "email_verified")
.put(UserAttributeMapper.USER_ATTRIBUTE, "emailVerified")
.build());

return Lists.newArrayList(attrMapper1, emailAttrMapper, nestedEmailAttrMapper, dottedEmailAttrMapper, emailVerifiedAttrMapper);
}

@Test
public void testImportEmailVerified() {
testValueMappingForImportSyncMode(ImmutableMap.<String, List<String>>builder()
.put("emailVerified", ImmutableList.<String>builder().add("true").build())
.build(),
ImmutableMap.<String, List<String>>builder()
.put("emailVerified", ImmutableList.<String>builder().add("false").build())
.build()
);
}

@Test
public void testForceEmailVerified() {
testValueMappingForForceSyncMode(ImmutableMap.<String, List<String>>builder()
.put("emailVerified", ImmutableList.<String>builder().add("true").build())
.build(),
ImmutableMap.<String, List<String>>builder()
.put("emailVerified", ImmutableList.<String>builder().add("false").build())
.build()
);
}

}
0