Example usage for org.springframework.security.crypto.password PasswordEncoder matches

List of usage examples for org.springframework.security.crypto.password PasswordEncoder matches

Introduction

In this page you can find the example usage for org.springframework.security.crypto.password PasswordEncoder matches.

Prototype

boolean matches(CharSequence rawPassword, String encodedPassword);

Source Link

Document

Verify the encoded password obtained from storage matches the submitted raw password after it too is encoded.

Usage

From source file:org.wallride.web.controller.guest.user.PasswordUpdateController.java

@RequestMapping(method = RequestMethod.PUT)
public String update(@Validated @ModelAttribute(FORM_MODEL_KEY) PasswordUpdateForm form, BindingResult errors,
        AuthorizedUser authorizedUser, RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form);
    redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors);

    if (!errors.hasFieldErrors("newPassword")) {
        if (!ObjectUtils.nullSafeEquals(form.getNewPassword(), form.getNewPasswordRetype())) {
            errors.rejectValue("newPasswordRetype", "MatchRetype");
        }/*from   ww w  . ja va  2 s  .c o  m*/
    }

    if (!errors.hasErrors()) {
        User user = userService.getUserById(authorizedUser.getId());
        PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
        if (!passwordEncoder.matches(form.getCurrentPassword(), user.getLoginPassword())) {
            errors.rejectValue("currentPassword", "MatchCurrentPassword");
        }
    }

    if (errors.hasErrors()) {
        return "redirect:/settings/password?step.edit";
    }

    PasswordUpdateRequest request = new PasswordUpdateRequest().withUserId(authorizedUser.getId())
            .withPassword(form.getNewPassword());
    userService.updatePassword(request, authorizedUser);

    redirectAttributes.getFlashAttributes().clear();
    redirectAttributes.addFlashAttribute("updatedPassword", true);
    return "redirect:/settings/password";
}

From source file:com.chevres.rss.restapi.dao.impl.UserDAOImplTest.java

/**
 * Test of updateUser method, of class UserDAOImpl.
 */// w w w .ja  va 2 s  .  c om
@Test
public void testUpdateUser() {
    User oldUser = userDao.findByUsername("user1");
    User newUser = new User();
    newUser.setUsername("Anthony");
    newUser.setPassword("updatepwd");
    newUser.setType("admin");
    userDao.updateUser(oldUser, newUser, true);

    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    boolean doesMatch = passwordEncoder.matches("updatepwd", oldUser.getPassword());

    assertEquals(oldUser.getUsername(), "Anthony");
    assertTrue(doesMatch);
    assertEquals(oldUser.getType(), "admin");
}

From source file:com.chevres.rss.restapi.dao.impl.UserDAOImpl.java

@Override
public User findByUsernameAndPassword(String username, String password) {
    Session session = this.getSessionFactory().openSession();
    try {/*  www .  j a  v  a  2s .c om*/
        Criteria criteria = session.createCriteria(User.class);
        User user = (User) criteria.add(Restrictions.eq("username", username)).uniqueResult();

        if (user != null) {
            PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean doesMatch = passwordEncoder.matches(password, user.getPassword());
            return doesMatch ? user : null;
        }
    } catch (Exception e) {
        throw e;
    } finally {
        session.close();
    }
    return null;
}

From source file:com.abixen.platform.core.service.impl.UserServiceImpl.java

@Override
public UserChangePasswordForm changeUserPassword(User user, UserChangePasswordForm userChangePasswordForm) {
    log.info("changeUserPassword()");

    PasswordEncoder encoder = new BCryptPasswordEncoder();
    String password = userChangePasswordForm.getCurrentPassword();
    if (!encoder.matches(password, user.getPassword())) {
        throw new UsernameNotFoundException("Wrong username and / or password.");
    }/*from   w ww .j ava  2 s .c  om*/

    user.setPassword(encoder.encode(userChangePasswordForm.getNewPassword()));
    updateUser(user);

    return userChangePasswordForm;
}

From source file:org.web4thejob.security.SpringSecurityService.java

@Override
public boolean isPasswordValid(UserIdentity userIdentity, String rawPassword) {
    PasswordEncoder passwordEncoder;

    try {/*ww w .ja v  a 2s  .c  om*/
        passwordEncoder = ContextUtil.getBean(PasswordEncoder.class);
    } catch (NoSuchBeanDefinitionException e) {
        return true;
    }

    return passwordEncoder.matches(rawPassword, userIdentity.getPassword());
}

From source file:com.abixen.platform.core.domain.model.User.java

public void changePassword(String currentPassword, String newPassword) {
    final PasswordEncoder encoder = new BCryptPasswordEncoder();
    if (!encoder.matches(currentPassword, getPassword())) {
        throw new UsernameNotFoundException("Wrong username and / or password.");
    }//  w ww.  j  a  va  2  s  . c  o m

    setPassword(encoder.encode(newPassword));
}

From source file:org.openwms.core.uaa.User.java

/**
 * Checks if the new password is a valid and change the password of this User.
 *
 * @param encodedPassword The new encoded password of this User
 * @throws InvalidPasswordException in case changing the password is not allowed or the new password is not valid
 *///from  w  w w  .ja va 2s  .  c  o  m
public void changePassword(String encodedPassword, String rawPassword, PasswordEncoder encoder)
        throws InvalidPasswordException {
    if (persistedPassword != null && encoder.matches(rawPassword, persistedPassword)) {
        LOGGER.debug("Trying to set the new password equals to the current password");
        return;
    }
    validateAgainstPasswordHistory(rawPassword, encoder);
    storeOldPassword(this.password);
    persistedPassword = encodedPassword;
    this.password = encodedPassword;
    lastPasswordChange = new Date();
}

From source file:org.openwms.core.uaa.User.java

/**
 * Check whether the new password is in the history of former passwords.
 *
 * @param rawPassword The password to verify
 * @return {@literal true} if the password is valid, otherwise {@literal false}
 *///from  www .  ja v  a  2s  . c o m
protected void validateAgainstPasswordHistory(String rawPassword, PasswordEncoder encoder)
        throws InvalidPasswordException {
    for (UserPassword up : passwords) {
        if (encoder.matches(rawPassword, up.getPassword())) {
            throw new InvalidPasswordException("Password is not confirm with defined rules");
        }
    }
}

From source file:org.alfresco.repo.security.authentication.CompositePasswordEncoder.java

/**
 * Does the password match?//from  w ww  .j ava  2  s .co  m
 * @param encoderKey the encoder to use
 * @param rawPassword  mandatory password
 * @param encodedPassword mandatory hashed version
 * @param salt optional salt
 * @return true if they match
 */
protected boolean matches(String encoderKey, String rawPassword, String encodedPassword, Object salt) {
    ParameterCheck.mandatoryString("rawPassword", rawPassword);
    ParameterCheck.mandatoryString("encodedPassword", encodedPassword);
    ParameterCheck.mandatoryString("encoderKey", encoderKey);
    Object encoder = encoders.get(encoderKey);
    if (encoder == null)
        throw new AlfrescoRuntimeException("Invalid matches encoder specified: " + encoderKey);
    if (encoder instanceof net.sf.acegisecurity.providers.encoding.PasswordEncoder) {
        net.sf.acegisecurity.providers.encoding.PasswordEncoder pEncoder = (net.sf.acegisecurity.providers.encoding.PasswordEncoder) encoder;
        if (MD4_KEY.equals(encoderKey)) {
            //In the past MD4 password encoding didn't use a SALT
            salt = null;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Matching using acegis PasswordEncoder: " + encoderKey);
        }
        return pEncoder.isPasswordValid(encodedPassword, rawPassword, salt);
    }
    if (encoder instanceof org.springframework.security.crypto.password.PasswordEncoder) {
        org.springframework.security.crypto.password.PasswordEncoder passEncoder = (org.springframework.security.crypto.password.PasswordEncoder) encoder;
        if (logger.isDebugEnabled()) {
            logger.debug("Matching using spring PasswordEncoder: " + encoderKey);
        }
        return passEncoder.matches(rawPassword, encodedPassword);
    }
    throw new AlfrescoRuntimeException("Unsupported encoder for matching: " + encoderKey);
}