Java Code Examples for org.keycloak.models.UserCredentialModel#password()

The following examples show how to use org.keycloak.models.UserCredentialModel#password() . 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: 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 2
Source File: ApplianceBootstrap.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void createMasterRealmUser(String username, String password) {
    RealmModel realm = session.realms().getRealm(Config.getAdminRealm());
    session.getContext().setRealm(realm);

    if (session.users().getUsersCount(realm) > 0) {
        throw new IllegalStateException("Can't create initial user as users already exists");
    }

    UserModel adminUser = session.users().addUser(realm, username);
    adminUser.setEnabled(true);

    UserCredentialModel usrCredModel = UserCredentialModel.password(password);
    session.userCredentialManager().updateCredential(realm, adminUser, usrCredModel);

    RoleModel adminRole = realm.getRole(AdminRoles.ADMIN);
    adminUser.grantRole(adminRole);
}
 
Example 3
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 4
Source File: AccountFormService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Update account password
 * <p>
 * Form params:
 * <p>
 * password - old password
 * password-new
 * pasword-confirm
 *
 * @param formData
 * @return
 */
@Path("password")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processPasswordUpdate(final MultivaluedMap<String, String> formData) {
    if (auth == null) {
        return login("password");
    }

    auth.require(AccountRoles.MANAGE_ACCOUNT);

    csrfCheck(formData);
    UserModel user = auth.getUser();

    boolean requireCurrent = isPasswordSet(session, realm, user);
    account.setPasswordSet(requireCurrent);

    String password = formData.getFirst("password");
    String passwordNew = formData.getFirst("password-new");
    String passwordConfirm = formData.getFirst("password-confirm");

    EventBuilder errorEvent = event.clone().event(EventType.UPDATE_PASSWORD_ERROR)
            .client(auth.getClient())
            .user(auth.getSession().getUser());

    if (requireCurrent) {
        if (Validation.isBlank(password)) {
            setReferrerOnPage();
            errorEvent.error(Errors.PASSWORD_MISSING);
            return account.setError(Status.OK, Messages.MISSING_PASSWORD).createResponse(AccountPages.PASSWORD);
        }

        UserCredentialModel cred = UserCredentialModel.password(password);
        if (!session.userCredentialManager().isValid(realm, user, cred)) {
            setReferrerOnPage();
            errorEvent.error(Errors.INVALID_USER_CREDENTIALS);
            return account.setError(Status.OK, Messages.INVALID_PASSWORD_EXISTING).createResponse(AccountPages.PASSWORD);
        }
    }

    if (Validation.isBlank(passwordNew)) {
        setReferrerOnPage();
        errorEvent.error(Errors.PASSWORD_MISSING);
        return account.setError(Status.OK, Messages.MISSING_PASSWORD).createResponse(AccountPages.PASSWORD);
    }

    if (!passwordNew.equals(passwordConfirm)) {
        setReferrerOnPage();
        errorEvent.error(Errors.PASSWORD_CONFIRM_ERROR);
        return account.setError(Status.OK, Messages.INVALID_PASSWORD_CONFIRM).createResponse(AccountPages.PASSWORD);
    }

    try {
        session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(passwordNew, false));
    } catch (ReadOnlyException mre) {
        setReferrerOnPage();
        errorEvent.error(Errors.NOT_ALLOWED);
        return account.setError(Response.Status.BAD_REQUEST, Messages.READ_ONLY_PASSWORD).createResponse(AccountPages.PASSWORD);
    } catch (ModelException me) {
        ServicesLogger.LOGGER.failedToUpdatePassword(me);
        setReferrerOnPage();
        errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED);
        return account.setError(Response.Status.NOT_ACCEPTABLE, me.getMessage(), me.getParameters()).createResponse(AccountPages.PASSWORD);
    } catch (Exception ape) {
        ServicesLogger.LOGGER.failedToUpdatePassword(ape);
        setReferrerOnPage();
        errorEvent.detail(Details.REASON, ape.getMessage()).error(Errors.PASSWORD_REJECTED);
        return account.setError(Response.Status.INTERNAL_SERVER_ERROR, ape.getMessage()).createResponse(AccountPages.PASSWORD);
    }

    List<UserSessionModel> sessions = session.sessions().getUserSessions(realm, user);
    for (UserSessionModel s : sessions) {
        if (!s.getId().equals(auth.getSession().getId())) {
            AuthenticationManager.backchannelLogout(session, realm, s, session.getContext().getUri(), clientConnection, headers, true);
        }
    }

    event.event(EventType.UPDATE_PASSWORD).client(auth.getClient()).user(auth.getUser()).success();

    setReferrerOnPage();
    return account.setPasswordSet(true).setSuccess(Messages.ACCOUNT_PASSWORD_UPDATED).createResponse(AccountPages.PASSWORD);
}