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

The following examples show how to use org.keycloak.models.UserModel#setSingleAttribute() . 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: SamlProtocol.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to retrieve the persistent type NameId as follows:
 *
 * <ol>
 *     <li>saml.persistent.name.id.for.$clientId user attribute</li>
 *     <li>saml.persistent.name.id.for.* user attribute</li>
 *     <li>G-$randomUuid</li>
 * </ol>
 *
 * If a randomUuid is generated, an attribute for the given saml.persistent.name.id.for.$clientId will be generated,
 * otherwise no state change will occur with respect to the user's attributes.
 *
 * @return the user's persistent NameId
 */
protected String getPersistentNameId(final CommonClientSessionModel clientSession, final UserSessionModel userSession) {
    // attempt to retrieve the UserID for the client-specific attribute
    final UserModel user = userSession.getUser();
    final String clientNameId = String.format("%s.%s", SAML_PERSISTENT_NAME_ID_FOR,
            clientSession.getClient().getClientId());
    String samlPersistentNameId = user.getFirstAttribute(clientNameId);
    if (samlPersistentNameId != null) {
        return samlPersistentNameId;
    }

    // check for a wildcard attribute
    final String wildcardNameId = String.format("%s.*", SAML_PERSISTENT_NAME_ID_FOR);
    samlPersistentNameId = user.getFirstAttribute(wildcardNameId);
    if (samlPersistentNameId != null) {
        return samlPersistentNameId;
    }

    // default to generated.  "G-" stands for "generated"
    samlPersistentNameId = "G-" + UUID.randomUUID().toString();
    user.setSingleAttribute(clientNameId, samlPersistentNameId);
    return samlPersistentNameId;
}
 
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: KerberosFederationProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected UserModel importUserToKeycloak(RealmModel realm, String username) {
    // Just guessing email from kerberos realm
    String email = username + "@" + kerberosConfig.getKerberosRealm().toLowerCase();

    logger.debugf("Creating kerberos user: %s, email: %s to local Keycloak storage", username, email);
    UserModel user = session.userLocalStorage().addUser(realm, username);
    user.setEnabled(true);
    user.setEmail(email);
    user.setFederationLink(model.getId());
    user.setSingleAttribute(KERBEROS_PRINCIPAL, username + "@" + kerberosConfig.getKerberosRealm());

    if (kerberosConfig.isUpdateProfileFirstLogin()) {
        user.addRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE);
    }

    return validate(realm, user);
}
 
Example 5
Source File: RegistrationValidateMobileFormAction.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void success(FormContext context) {

    // called after successful validation

    UserModel user = context.getUser();
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    user.setSingleAttribute(MOBILE_NUMBER_USER_ATTRIBUTE, formData.getFirst(MOBILE_NUMBER_FIELD));
}
 
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: DefaultLocaleUpdaterProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void updateUsersLocale(UserModel user, String locale) {
    if (!locale.equals(user.getFirstAttribute("locale"))) {
        try {
            user.setSingleAttribute(UserModel.LOCALE, locale);
            updateLocaleCookie(locale);
        } catch (ReadOnlyException e) {
            logger.debug("Attempt to store 'locale' attribute to read only user model. Ignoring exception", e);
        }
    }
    logger.debugv("Setting locale for user {0} to {1}", user.getUsername(), locale);
}
 
Example 8
Source File: LoginNotifyEmailAuthenticator.java    From keycloak-extension-playground with Apache License 2.0 4 votes vote down vote up
protected void updateLastLoginTimeForUser(UserModel user, long currentLoginTime) {
    user.setSingleAttribute("lastLoginTime", String.valueOf(currentLoginTime));
}
 
Example 9
Source File: HardcodedAttributeMapper.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void updateBrokeredUser(KeycloakSession session, RealmModel realm, UserModel user, IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
    String attribute = mapperModel.getConfig().get(ATTRIBUTE);
    String attributeValue = mapperModel.getConfig().get(ATTRIBUTE_VALUE);
    user.setSingleAttribute(attribute, attributeValue);
}