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

The following examples show how to use org.keycloak.models.UserModel#setEmail() . 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: PassThroughRegistration.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void authenticate(AuthenticationFlowContext context) {
    context.getEvent().detail(Details.USERNAME, username)
            .detail(Details.REGISTER_METHOD, "form")
            .detail(Details.EMAIL, email)
    ;
    UserModel user = context.getSession().users().addUser(context.getRealm(), username);
    user.setEnabled(true);

    user.setEmail(email);
    context.getAuthenticationSession().setClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM, username);
    context.setUser(user);
    context.getEvent().user(user);
    context.getEvent().success();
    context.newEvent().event(EventType.LOGIN);
    context.getEvent().client(context.getAuthenticationSession().getClient().getClientId())
            .detail(Details.REDIRECT_URI, context.getAuthenticationSession().getRedirectUri())
            .detail(Details.AUTH_METHOD, context.getAuthenticationSession().getProtocol());
    String authType = context.getAuthenticationSession().getAuthNote(Details.AUTH_TYPE);
    if (authType != null) {
        context.getEvent().detail(Details.AUTH_TYPE, authType);
    }
    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: UserCommands.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void createUsersInBatch(KeycloakSession session, int first, int count) {
    RealmModel realm = session.realms().getRealmByName(realmName);
    if (realm == null) {
        log.errorf("Unknown realm: %s", realmName);
        throw new HandledException();
    }

    Set<RoleModel> roles = findRoles(realm, roleNames);

    int last = first + count;
    for (int counter = first; counter < last; counter++) {
        String username = usernamePrefix + counter;
        UserModel user = session.users().addUser(realm, username);
        user.setEnabled(true);
        user.setEmail(username + "@keycloak.org");
        UserCredentialModel passwordCred = UserCredentialModel.password(password);
        session.userCredentialManager().updateCredential(realm, user, passwordCred);

        for (RoleModel role : roles) {
            user.grantRole(role);
        }
    }
    log.infof("Users from %s to %s created", usernamePrefix + first, usernamePrefix + (last - 1));
}
 
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: 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: MigrateTo1_4_0.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void migrateUsers(KeycloakSession session, RealmModel realm) {
    List<UserModel> users = session.userLocalStorage().getUsers(realm, false);
    for (UserModel user : users) {
        String email = user.getEmail();
        email = KeycloakModelUtils.toLowerCaseSafe(email);
        if (email != null && !email.equals(user.getEmail())) {
            user.setEmail(email);
            UserCache userCache = session.userCache();
            if (userCache != null) {
                userCache.evict(realm, user);
            }
        }
    }
}
 
Example 7
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void setupRealm(KeycloakSession session){
    RealmModel realm = session.realms().getRealmByName("test");
    UserModel user1 = session.users().addUser(realm, "user1");
    user1.setEmail("user1@localhost");
    UserModel user2 = session.users().addUser(realm, "user2");
    user2.setEmail("user2@localhost");
}
 
Example 8
Source File: LDAPTestUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static UserModel addLocalUser(KeycloakSession session, RealmModel realm, String username, String email, String password) {
    UserModel user = session.userLocalStorage().addUser(realm, username);
    user.setEmail(email);
    user.setEnabled(true);

    UserCredentialModel creds = UserCredentialModel.password(password);

    session.userCredentialManager().updateCredential(realm, user, creds);
    return user;
}
 
Example 9
Source File: RegistrationProfile.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void success(FormContext context) {
    UserModel user = context.getUser();
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    user.setFirstName(formData.getFirst(RegistrationPage.FIELD_FIRST_NAME));
    user.setLastName(formData.getFirst(RegistrationPage.FIELD_LAST_NAME));
    user.setEmail(formData.getFirst(RegistrationPage.FIELD_EMAIL));
}
 
Example 10
Source File: RegistrationUserCreation.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void success(FormContext context) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    String email = formData.getFirst(Validation.FIELD_EMAIL);
    String username = formData.getFirst(RegistrationPage.FIELD_USERNAME);
    if (context.getRealm().isRegistrationEmailAsUsername()) {
        username = formData.getFirst(RegistrationPage.FIELD_EMAIL);
    }
    context.getEvent().detail(Details.USERNAME, username)
            .detail(Details.REGISTER_METHOD, "form")
            .detail(Details.EMAIL, email)
    ;
    UserModel user = context.getSession().users().addUser(context.getRealm(), username);
    user.setEnabled(true);

    user.setEmail(email);
    context.getAuthenticationSession().setClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM, username);
    AttributeFormDataProcessor.process(formData, context.getRealm(), user);
    context.setUser(user);
    context.getEvent().user(user);
    context.getEvent().success();
    context.newEvent().event(EventType.LOGIN);
    context.getEvent().client(context.getAuthenticationSession().getClient().getClientId())
            .detail(Details.REDIRECT_URI, context.getAuthenticationSession().getRedirectUri())
            .detail(Details.AUTH_METHOD, context.getAuthenticationSession().getProtocol());
    String authType = context.getAuthenticationSession().getAuthNote(Details.AUTH_TYPE);
    if (authType != null) {
        context.getEvent().detail(Details.AUTH_TYPE, authType);
    }
}
 
Example 11
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 12
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();
        }
    }
}