8000 Being possible to accept terms and conditions befure User is saved in… by cgeorgilakis · Pull Request #29975 · 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 @@ -37,6 +37,8 @@
public interface LoginFormsProvider extends Provider {

String UPDATE_PROFILE_CONTEXT_ATTR = "updateProfileCtx";
String UPDATE_PROFILE_FIRST_LOGIN = "updateProfileFirstLogin";
String TERMS_ACCEPTANCE_REQUIRED = "termsAcceptanceRequired";

String IDENTITY_PROVIDER_BROKER_CONTEXT = "identityProviderBrokerCtx";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,7 @@ public static void firstBrokerLoginFlow(RealmModel realm, boolean migrate) {
reviewProfileConfig.setAlias(IDP_REVIEW_PROFILE_CONFIG_ALIAS);
Map<String, String> config = new HashMap<>();
config.put("update.profile.on.first.login", IdentityProviderRepresentation.UPFLM_MISSING);
config.put("terms_and_conditions", "false");
reviewProfileConfig.setConfig(config);
reviewProfileConfig = realm.addAuthenticatorConfig(reviewProfileConfig);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,21 @@ public interface UserProfileProvider extends Provider {
*/
UserProfile create(UserProfileContext context, Map<String, ?> attributes, UserModel user);

/**
* <p>Creates a new {@link UserProfile} instance for a given {@code context} and {@code attributes} for update purposes.
*
* <p>Instances created from this method are going to run validations and updates based on the given {@code user}. This
* might be useful when updating an existing user.
*
* @param context the context
* @param attributes the attributes to associate with the instance returned from this method
* @param user the user to eventually update with the given {@code attributes}
* @param terms if terms and condition required action user attribute neeed to be saved
*
* @return the user profile instance
*/
UserProfile create(UserProfileContext context, Map<String, ?> attributes, UserModel user, boolean terms);

/**
* Get current UserProfile configuration.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@
import org.jboss.logging.Logger;
import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext;
import org.keycloak.authentication.requiredactions.TermsAndConditions;
import org.keycloak.broker.provider.BrokeredIdentityContext;
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.common.util.Time;
import org.keycloak.events.Details;
import org.keycloak.events.EventBuilder;
import org.keycloak.events.EventType;
Expand All @@ -42,6 +45,7 @@
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
Expand All @@ -54,7 +58,9 @@
public class IdpReviewProfileAuthenticator extends AbstractIdpAuthenticator {

private static final Logger logger = Logger.getLogger(IdpReviewProfileAuthenticator.class);

private static final String TERMS_FIELD ="termsAccepted";
private boolean enabledRequiredAction= false;
private boolean updateProfile= false;
@Override
public boolean requiresUser() {
return false;
Expand All @@ -63,14 +69,22 @@ public boolean requiresUser() {
@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext userCtx, BrokeredIdentityContext brokerContext) {
IdentityProviderModel idpConfig = brokerContext.getIdpConfig();
enabledRequiredAction = context.getRealm().getRequiredActionProviderByAlias(UserModel.RequiredAction.TERMS_AND_CONDITIONS.name()).isEnabled() && Boolean.valueOf(context.getAuthenticatorConfig().getConfig().get(IdpReviewProfileAuthenticatorFactory.TERMS_AND_CONDITIONS));
updateProfile = requiresUpdateProfilePage(context.getAuthenticatorConfig(), context, userCtx);

if (requiresUpdateProfilePage(context, userCtx, brokerContext)) {
if ( enabledRequiredAction || updateProfile) {

// set up form only if
// 1. terms and conditions is enabled and terms and condition configuration is true
// 2. ENFORCE_UPDATE_PROFILE is true
// 3. based on UPDATE_PROFILE_ON_FIRST_LOGIN value and IdP release data
logger.debugf("Identity provider '%s' requires update profile action for broker user '%s'.", idpConfig.getAlias(), userCtx.getUsername());

// No formData for first render. The profile is rendered from userCtx
Response challengeResponse = context.form()
.setAttribute(LoginFormsProvider.UPDATE_PROFILE_CONTEXT_ATTR, userCtx)
.setAttribute(LoginFormsProvider.UPDATE_PROFILE_FIRST_LOGIN, updateProfile)
.setAttribute(LoginFormsProvider.TERMS_ACCEPTANCE_REQUIRED, enabledRequiredAction)
.setFormData(null)
.createUpdateProfilePage();
context.challenge(challengeResponse);
Expand All @@ -80,21 +94,19 @@ protected void authenticateImpl(AuthenticationFlowContext context, SerializedBro
}
}

protected boolean requiresUpdateProfilePage(AuthenticationFlowContext context, SerializedBrokeredIdentityContext userCtx, BrokeredIdentityContext brokerContext) {
String enforceUpdateProfile = context.getAuthenticationSession().getAuthNote(ENFORCE_UPDATE_PROFILE);
if (Boolean.parseBoolean(enforceUpdateProfile)) {
protected boolean requiresUpdateProfilePage(AuthenticatorConfigModel authenticatorConfig, AuthenticationFlowContext context, SerializedBrokeredIdentityContext userCtx) {
if (Boolean.parseBoolean(context.getAuthenticationSession().getAuthNote(ENFORCE_UPDATE_PROFILE))) {
return true;
}

String updateProfileFirstLogin;
AuthenticatorConfigModel authenticatorConfig = context.getAuthenticatorConfig();
if (authenticatorConfig == null || !authenticatorConfig.getConfig().containsKey(IdpReviewProfileAuthenticatorFactory.UPDATE_PROFILE_ON_FIRST_LOGIN)) {
updateProfileFirstLogin = IdentityProviderRepresentation.UPFLM_MISSING;
} else {
updateProfileFirstLogin = authenticatorConfig.getConfig().get(IdpReviewProfileAuthenticatorFactory.UPDATE_PROFILE_ON_FIRST_LOGIN);
}

if(IdentityProviderRepresentation.UPFLM_MISSING.equals(updateProfileFirstLogin)) {
if (IdentityProviderRepresentation.UPFLM_MISSING.equals(updateProfileFirstLogin)) {
try {
UserProfileProvider profileProvider = context.getSession().getProvider(UserProfileProvider.class);
profileProvider.create(UserProfileContext.IDP_REVIEW, userCtx.getAttributes()).validate();
Expand All @@ -112,6 +124,40 @@ protected void actionImpl(AuthenticationFlowContext context, SerializedBrokeredI
EventBuilder event = context.getEvent();
event.event(EventType.UPDATE_PROFILE).detail(Details.CONTEXT, UserProfileContext.IDP_REVIEW.name());
MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
//for security reason when updateProfile is false, keep old values equal to broken data
if (!updateProfile) {
formData.put("username", Stream.of(userCtx.getUsername()).toList());
if (userCtx.getEmail() != null) {
formData.put("email", Stream.of(userCtx.getEmail()).toList());
} else {
formData.remove("email");
}
if (userCtx.getFirstName() != null) {
formData.put("firstName", Stream.of(userCtx.getFirstName()).toList());
} else {
formData.remove("firstName");
}
if (userCtx.getLastName() != null) {
formData.put("lastName", Stream.of(userCtx.getLastName()).toList());
} else {
formData.remove("lastName");
}
userCtx.getAttributes().entrySet().stream().forEach(x -> formData.put(x.getKey(), x.getValue()));
}

if (enabledRequiredAction && ! formData.containsKey(TERMS_FIELD)) {
Response challengeForTerms = context.form()
.setErrors(Collections.singletonList(new FormMessage(TERMS_FIELD, "termsAcceptanceRequired")))
.setAttribute(LoginFormsProvider.UPDATE_PROFILE_CONTEXT_ATTR, userCtx)
.setAttribute(LoginFormsProvider.UPDATE_PROFILE_FIRST_LOGIN, updateProfile)
.setAttribute(LoginFormsProvider.TERMS_ACCEPTANCE_REQUIRED, enabledRequiredAction)
.setFormData(formData)
.createUpdateProfilePage();

context.challenge(challengeForTerms);

return;
}
UserModelDelegate updatedProfile = new UserModelDelegate(null) {

@Override
Expand Down Expand Up @@ -198,7 +244,13 @@ public String getFederationLink() {
UserProfileProvider profileProvider = context.getSession().getProvider(UserProfileProvider.class);
Map<String, List<String>> attributes = new HashMap<>(formData);
attributes.putIfAbsent(UserModel.USERNAME, Collections.singletonList(updatedProfile.getUsername()));
UserProfile profile = profileProvider.create(UserProfileContext.IDP_REVIEW, attributes, updatedProfile);
if (attributes.containsKey(TERMS_FIELD)) {
//if form contains terms and condition remove this field and add TermsAndConditions.USER_ATTRIBUTE
attributes.remove(TERMS_FIELD);
attributes.put(TermsAndConditions.USER_ATTRIBUTE, Arrays.asList(Integer.toString(Time.currentTime())));
}

UserProfile profile = profileProvider.create(UserProfileContext.IDP_REVIEW, attributes, updatedProfile, formData.containsKey(TERMS_FIELD));

try {
String oldEmail = userCtx.getEmail();
Expand All @@ -215,6 +267,8 @@ public String getFederationLink() {
Response challenge = context.form()
.setErrors(errors)
.setAttribute(LoginFormsProvider.UPDATE_PROFILE_CONTEXT_ATTR, userCtx)
.setAttribute(LoginFormsProvider.UPDATE_PROFILE_FIRST_LOGIN, updateProfile)
.setAttribute(LoginFormsProvider.TERMS_ACCEPTANCE_REQUIRED, enabledRequiredAction)
.setFormData(formData)
.createUpdateProfilePage();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public class IdpReviewProfileAuthenticatorFactory implements AuthenticatorFactor
static IdpReviewProfileAuthentica 10BC8 tor SINGLETON = new IdpReviewProfileAuthenticator();

public static final String UPDATE_PROFILE_ON_FIRST_LOGIN = "update.profile.on.first.login";
public static final String TERMS_AND_CONDITIONS = "terms_and_conditions";

@Override
public Authenticator create(KeycloakSession session) {
Expand Down Expand Up @@ -110,7 +111,13 @@ public boolean isUserSetupAllowed() {
+ " page for reviewing profile will be displayed and user can review and update his profile. Value 'off' means that page won't be displayed."
+ " Value 'missing' means that page is displayed just when some required attribute is missing (wasn't downloaded from identity provider). Value 'missing' is the default one."
+ " WARN: In case that user clicks 'Review profile info' on link duplications page, the update page will be always displayed. You would need to disable this authenticator to never display the page.");

configProperties.add(property);
property = new ProviderConfigProperty();
property.setName(TERMS_AND_CONDITIONS);
property.setLabel("Accept Terms and Conditions");
property.setType(ProviderConfigProperty.BOOLEAN_TYPE);
property.setHelpText("Enable this option to require users to accept terms and conditions before their profile is recorded."
+ "This ensures compliance with data regulation frameworks like GDPR on first login. You also need to enable the 'Terms and Conditions' Required action for this to take effect.");
configProperties.add(property);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import static org.keycloak.common.util.ObjectUtil.isBlank;
import static org.keycloak.protocol.oidc.TokenManager.getRequestedClientScopes;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
Expand All @@ -32,8 +33,10 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.keycloak.authentication.requiredactions.TermsAndConditions;
import org.keycloak.component.ComponentModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
Expand All @@ -52,6 +55,7 @@
import org.keycloak.userprofile.validator.AttributeRequiredByMetadataValidator;
import org.keycloak.userprofile.validator.ImmutableAttributeValidator;
import org.keycloak.userprofile.validator.MultiValueValidator;
import org.keycloak.userprofile.validator.ReadOnlyAttributeUnchangedValidator;
import org.keycloak.util.JsonSerialization;
import org.keycloak.validate.AbstractSimpleValidator;
import org.keycloak.validate.ValidatorConfig;
Expand Down Expand Up @@ -126,6 +130,26 @@ public UserProfile create(UserProfileContext context, Map<String, ?> attributes)
return createUserProfile(context, attributes, null);
}

@Override
public UserProfile create(UserProfileContext context, Map<String, ?> attributes, UserModel user, boolean terms) {
return terms ? createUserProfileWithTerms(context, attributes, user) : createUserProfile(context, attributes, user);
}

private UserProfile createUserProfileWithTerms(UserProfileContext context, Map<String, ?> attributes, UserModel user) {
UserProfileMetadata metadata = configureUserProfile(contextualMetadataRegistry.get(context), session);
List<AttributeValidatorMetadata> readonlyValidators = new ArrayList<>();
readonlyValidators.add(createReadOnlyAttributeUnchangedValidator(DeclarativeUserProfileProviderFactory.readOnlyAttributesPattern));
metadata.addAttribute(TermsAndConditions.USER_ATTRIBUTE, 1000, readonlyValidators);
Attributes profileAttributes = createAttributes(context, attributes, user, metadata);
return new DefaultUserProfile(metadata, profileAttributes, createUserFactory(), user, session);
}

private AttributeValidatorMetadata createReadOnlyAttributeUnchangedValidator(Pattern pattern) {
return new AttributeValidatorMetadata(ReadOnlyAttributeUnchangedValidator.ID,
ValidatorConfig.builder().config(ReadOnlyAttributeUnchangedValidator.CFG_PATTERN, pattern)
.build());
}

private UserProfile createUserProfile(UserProfileContext context, Map<String, ?> attributes, UserModel user) {
UserProfileMetadata defaultMetadata = contextualMetadataRegistry.get(context);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public class DeclarativeUserProfileProviderFactory implements UserProfileProvide
*/
private static final String[] DEFAULT_READ_ONLY_ATTRIBUTES = { "KERBEROS_PRINCIPAL", "LDAP_ID", "LDAP_ENTRY_DN", "CREATED_TIMESTAMP", "createTimestamp", "modifyTimestamp", "userCertificate", "saml.persistent.name.id.for.*", "ENABLED", "EMAIL_VERIFIED", "disabledReason" };
private static final String[] DEFAULT_ADMIN_READ_ONLY_ATTRIBUTES = { "KERBEROS_PRINCIPAL", "LDAP_ID", "LDAP_ENTRY_DN", "CREATED_TIMESTAMP", "createTimestamp", "modifyTimestamp" };
private static final Pattern readOnlyAttributesPattern = getRegexPatternString(DEFAULT_READ_ONLY_ATTRIBUTES);
public static final Pattern readOnlyAttributesPattern = getRegexPatternString(DEFAULT_READ_ONLY_ATTRIBUTES);
private static final Pattern adminReadOnlyAttributesPattern = getRegexPatternString(DEFAULT_ADMIN_READ_ONLY_ATTRIBUTES);

private static volatile UPConfig PARSED_DEFAULT_RAW_CONFIG;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ public class UpdateAccountInformationPage extends LanguageComboboxAwarePage {

@FindBy(id = "department")
private WebElement departmentInput;

@FindBy(id = "termsAccepted")
private WebElement termsAccepted;

@FindBy(css = "input[type=\"submit\"]")
private WebElement submitButton;
Expand All @@ -45,6 +48,26 @@ public void updateAccountInformation(String userName,

clickLink(submitButton);
}

public void acceptTerms(String userName,
String email,
String firstName,
String lastName) {
usernameInput.clear();
usernameInput.sendKeys(userName);

emailInput.clear();
emailInput.sendKeys(email);

firstNameInput.clear();
firstNameInput.sendKeys(firstName);

lastNameInput.clear();
lastNameInput.sendKeys(lastName);
termsAccepted.click();

clickLink(submitButton);
}

public void updateAccountInformation(String userName,
String email,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public class InitialFlowsTest extends AbstractAuthenticationTest {
private HashMap<String, AuthenticatorConfigRepresentation> expectedConfigs = new HashMap<>();

{
expectedConfigs.put("idp-review-profile", newConfig("review profile config", new String[]{"update.profile.on.first.login", "missing"}));
expectedConfigs.put("idp-review-profile", newConfig("review profile config", new String[]{"update.profile.on.first.login", "missing","terms_and_conditions","false"}));
expectedConfigs.put("idp-create-user-if-unique", newConfig("create unique user config", new String[]{"require.password.update.after.registration", "false"}));
}

Expand Down
Loading
0