Java Code Examples for org.keycloak.models.UserModel#setAttribute()

The following examples show how to use org.keycloak.models.UserModel#setAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SetUserAttributeAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    // Retrieve configuration
    Map<String, String> config = context.getAuthenticatorConfig().getConfig();
    String attrName = config.get(SetUserAttributeAuthenticatorFactory.CONF_ATTR_NAME);
    String attrValue = config.get(SetUserAttributeAuthenticatorFactory.CONF_ATTR_VALUE);

    UserModel user = context.getUser();
    if (user.getAttribute(attrName) == null) {
        user.setSingleAttribute(attrName, attrValue);
    }
    else {
        List<String> attrValues = new ArrayList<>(user.getAttribute(attrName));
        if (!attrValues.contains(attrValue)) {
            attrValues.add(attrValue);
        }
        user.setAttribute(attrName, attrValues);
    }

    context.success();
}
 
Example 2
Source File: FailableHardcodedStorageProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public UserModel getUserByUsername(String uname, RealmModel realm) {
    checkForceFail();
    if (!username.equals(uname)) return null;
    UserModel local = session.userLocalStorage().getUserByUsername(uname, realm);
    if (local != null && !model.getId().equals(local.getFederationLink())) {
        throw new RuntimeException("local storage has wrong federation link");
    }
    if (local != null) return new Delegate(local);
    local = session.userLocalStorage().addUser(realm, uname);
    local.setEnabled(true);
    local.setFirstName(first);
    local.setLastName(last);
    local.setEmail(email);
    local.setFederationLink(model.getId());
    for (String key : attributes.keySet()) {
        List<String> values = attributes.get(key);
        if (values == null) continue;
        local.setAttribute(key, values);
    }
    return new Delegate(local);
}
 
Example 3
Source File: AbstractJsonUserAttributeMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
	String attribute = getAttribute(mapperModel);
	if (attribute == null) {
		return;
	}

	Object value = getJsonValue(mapperModel, context);
	if (value == null) {
		user.removeAttribute(attribute);
	} else if (value instanceof List) {
		user.setAttribute(attribute, (List<String>) value);
	} else {
		user.setSingleAttribute(attribute, value.toString());
	}
}
 
Example 4
Source File: UserAttributeMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
    String attribute = mapperModel.getConfig().get(USER_ATTRIBUTE);
    if(StringUtil.isNullOrEmpty(attribute)){
        return;
    }
    Object value = getClaimValue(mapperModel, context);
    List<String> values = toList(value);
    if (EMAIL.equalsIgnoreCase(attribute)) {
        setIfNotEmpty(user::setEmail, values);
    } else if (FIRST_NAME.equalsIgnoreCase(attribute)) {
        setIfNotEmpty(user::setFirstName, values);
    } else if (LAST_NAME.equalsIgnoreCase(attribute)) {
        setIfNotEmpty(user::setLastName, values);
    } else {
        List<String> current = user.getAttribute(attribute);
        if (!CollectionUtil.collectionEquals(values, current)) {
            user.setAttribute(attribute, values);
        } else if (values.isEmpty()) {
            user.removeAttribute(attribute);
        }
    }
}
 
Example 5
Source File: RemoteUserFederationProvider.java    From keycloak-user-migration-provider with Apache License 2.0 5 votes vote down vote up
private UserModel createUserModel(RealmModel realm, String rawUsername) throws NotFoundException {

        String username = rawUsername.toLowerCase().trim();
        FederatedUserModel remoteUser = federatedUserService.getUserDetails(username);
        LOG.infof("Creating user model for: %s", username);
        UserModel userModel = session.userStorage().addUser(realm, username);

        if (!username.equals(remoteUser.getEmail())) {
            throw new IllegalStateException(String.format("Local and remote users differ: [%s != %s]", username, remoteUser.getUsername()));
        }

        userModel.setFederationLink(model.getId());
        userModel.setEnabled(remoteUser.isEnabled());
        userModel.setEmail(username);
        userModel.setEmailVerified(remoteUser.isEmailVerified());
        userModel.setFirstName(remoteUser.getFirstName());
        userModel.setLastName(remoteUser.getLastName());

        if (remoteUser.getAttributes() != null) {
            Map<String, List<String>> attributes = remoteUser.getAttributes();
            for (String attributeName : attributes.keySet())
                userModel.setAttribute(attributeName, attributes.get(attributeName));
        }

        if (remoteUser.getRoles() != null) {
            for (String role : remoteUser.getRoles()) {
                RoleModel roleModel = realm.getRole(role);
                if (roleModel != null) {
                    userModel.grantRole(roleModel);
                    LOG.infof("Granted user %s, role %s", username, role);
                }
            }
        }

        return userModel;
    }
 
Example 6
Source File: PolicyEvaluationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void testCheckUserAttributes(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("authz-test");
    UserModel jdoe = session.users().getUserByUsername("jdoe", realm);

    jdoe.setAttribute("a1", Arrays.asList("1", "2"));
    jdoe.setSingleAttribute("a2", "3");

    session.getContext().setRealm(realm);
    AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
    ClientModel clientModel = session.realms().getClientByClientId("resource-server-test", session.getContext().getRealm());
    StoreFactory storeFactory = authorization.getStoreFactory();
    ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());
    JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();

    policyRepresentation.setName("testCheckUserAttributes");
    StringBuilder builder = new StringBuilder();

    builder.append("var realm = $evaluation.getRealm();");
    builder.append("var attributes = realm.getUserAttributes('jdoe');");
    builder.append("if (attributes.size() == 6 && attributes.containsKey('a1') && attributes.containsKey('a2') && attributes.get('a1').size() == 2 && attributes.get('a2').get(0).equals('3')) { $evaluation.grant(); }");

    policyRepresentation.setCode(builder.toString());

    Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
    PolicyProvider provider = authorization.getProvider(policy.getType());

    DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);

    provider.evaluate(evaluation);

    Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
}
 
Example 7
Source File: UserAttributeMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
    String attribute = mapperModel.getConfig().get(USER_ATTRIBUTE);
    if (StringUtil.isNullOrEmpty(attribute)) {
        return;
    }
    String attributeName = getAttributeNameFromMapperModel(mapperModel);
    List<String> attributeValuesInContext = findAttributeValuesInContext(attributeName, context);
    if (attribute.equalsIgnoreCase(EMAIL)) {
        setIfNotEmpty(user::setEmail, attributeValuesInContext);
    } else if (attribute.equalsIgnoreCase(FIRST_NAME)) {
        setIfNotEmpty(user::setFirstName, attributeValuesInContext);
    } else if (attribute.equalsIgnoreCase(LAST_NAME)) {
        setIfNotEmpty(user::setLastName, attributeValuesInContext);
    } else {
        List<String> currentAttributeValues = user.getAttributes().get(attribute);
        if (attributeValuesInContext == null) {
            // attribute no longer sent by brokered idp, remove it
            user.removeAttribute(attribute);
        } else if (currentAttributeValues == null) {
            // new attribute sent by brokered idp, add it
            user.setAttribute(attribute, attributeValuesInContext);
        } else if (!CollectionUtil.collectionEquals(attributeValuesInContext, currentAttributeValues)) {
            // attribute sent by brokered idp has different values as before, update it
            user.setAttribute(attribute, attributeValuesInContext);
        }
        // attribute already set
    }
}
 
Example 8
Source File: HardcodedAttributeMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void onImportUserFromLDAP(LDAPObject ldapUser, UserModel user, RealmModel realm, boolean isCreate) {
    String userModelAttrName = getUserModelAttribute();

    String attributeValue = getAttributeValue();
    Property<Object> userModelProperty = userModelProperties.get(userModelAttrName.toLowerCase());

    if (userModelProperty != null) {
        setPropertyOnUserModel(userModelProperty, user, attributeValue);
    } else {
        user.setAttribute(userModelAttrName, Arrays.asList(attributeValue));
    }
}
 
Example 9
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep) {
    convertDeprecatedSocialProviders(userRep);

    // Import users just to user storage. Don't federate
    UserModel user = session.userLocalStorage().addUser(newRealm, userRep.getId(), userRep.getUsername(), false, false);
    user.setEnabled(userRep.isEnabled() != null && userRep.isEnabled());
    user.setCreatedTimestamp(userRep.getCreatedTimestamp());
    user.setEmail(userRep.getEmail());
    if (userRep.isEmailVerified() != null) user.setEmailVerified(userRep.isEmailVerified());
    user.setFirstName(userRep.getFirstName());
    user.setLastName(userRep.getLastName());
    user.setFederationLink(userRep.getFederationLink());
    if (userRep.getAttributes() != null) {
        for (Map.Entry<String, List<String>> entry : userRep.getAttributes().entrySet()) {
            List<String> value = entry.getValue();
            if (value != null) {
                user.setAttribute(entry.getKey(), new ArrayList<>(value));
            }
        }
    }
    if (userRep.getRequiredActions() != null) {
        for (String requiredAction : userRep.getRequiredActions()) {
            try {
                user.addRequiredAction(UserModel.RequiredAction.valueOf(requiredAction.toUpperCase()));
            } catch (IllegalArgumentException iae) {
                user.addRequiredAction(requiredAction);
            }
        }
    }
    createCredentials(userRep, session, newRealm, user, false);
    createFederatedIdentities(userRep, session, newRealm, user);
    createRoleMappings(userRep, user, newRealm);
    if (userRep.getClientConsents() != null) {
        for (UserConsentRepresentation consentRep : userRep.getClientConsents()) {
            UserConsentModel consentModel = toModel(newRealm, consentRep);
            session.users().addConsent(newRealm, user.getId(), consentModel);
        }
    }

    if (userRep.getNotBefore() != null) {
        session.users().setNotBeforeForUser(newRealm, user, userRep.getNotBefore());
    }

    if (userRep.getServiceAccountClientId() != null) {
        String clientId = userRep.getServiceAccountClientId();
        ClientModel client = newRealm.getClientByClientId(clientId);
        if (client == null) {
            throw new RuntimeException("Unable to find client specified for service account link. Client: " + clientId);
        }
        user.setServiceAccountClientLink(client.getId());
    }
    createGroups(userRep, newRealm, user);
    return user;
}
 
Example 10
Source File: IdpCreateUserIfUniqueAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {

    KeycloakSession session = context.getSession();
    RealmModel realm = context.getRealm();

    if (context.getAuthenticationSession().getAuthNote(EXISTING_USER_INFO) != null) {
        context.attempted();
        return;
    }

    String username = getUsername(context, serializedCtx, brokerContext);
    if (username == null) {
        ServicesLogger.LOGGER.resetFlow(realm.isRegistrationEmailAsUsername() ? "Email" : "Username");
        context.getAuthenticationSession().setAuthNote(ENFORCE_UPDATE_PROFILE, "true");
        context.resetFlow();
        return;
    }

    ExistingUserInfo duplication = checkExistingUser(context, username, serializedCtx, brokerContext);

    if (duplication == null) {
        logger.debugf("No duplication detected. Creating account for user '%s' and linking with identity provider '%s' .",
                username, brokerContext.getIdpConfig().getAlias());

        UserModel federatedUser = session.users().addUser(realm, username);
        federatedUser.setEnabled(true);
        federatedUser.setEmail(brokerContext.getEmail());
        federatedUser.setFirstName(brokerContext.getFirstName());
        federatedUser.setLastName(brokerContext.getLastName());

        for (Map.Entry<String, List<String>> attr : serializedCtx.getAttributes().entrySet()) {
            federatedUser.setAttribute(attr.getKey(), attr.getValue());
        }

        AuthenticatorConfigModel config = context.getAuthenticatorConfig();
        if (config != null && Boolean.parseBoolean(config.getConfig().get(IdpCreateUserIfUniqueAuthenticatorFactory.REQUIRE_PASSWORD_UPDATE_AFTER_REGISTRATION))) {
            logger.debugf("User '%s' required to update password", federatedUser.getUsername());
            federatedUser.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
        }

        userRegisteredSuccess(context, federatedUser, serializedCtx, brokerContext);

        context.setUser(federatedUser);
        context.getAuthenticationSession().setAuthNote(BROKER_REGISTERED_NEW_USER, "true");
        context.success();
    } else {
        logger.debugf("Duplication detected. There is already existing user with %s '%s' .",
                duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue());

        // Set duplicated user, so next authenticators can deal with it
        context.getAuthenticationSession().setAuthNote(EXISTING_USER_INFO, duplication.serialize());
        //Only show error message if the authenticator was required
        if (context.getExecution().isRequired()) {
            Response challengeResponse = context.form()
                    .setError(Messages.FEDERATED_IDENTITY_EXISTS, duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue())
                    .createErrorPage(Response.Status.CONFLICT);
            context.challenge(challengeResponse);
            context.getEvent()
                    .user(duplication.getExistingUserId())
                    .detail("existing_" + duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue())
                    .removeDetail(Details.AUTH_METHOD)
                    .removeDetail(Details.AUTH_TYPE)
                    .error(Errors.FEDERATED_IDENTITY_EXISTS);
        } else {
            context.attempted();
        }
    }
}