0

Spring boot application, user want to change the password after login but i the function is not changing the password.

    @PostMapping("/settings/passwordupdate")
    public String PasswordUpdate(@RequestParam("oldPassword") String oldPassword,
            @RequestParam("newPassword") String newPassword, Principal principal) {

         
        String userName = principal.getName();
        User currentUser = serviceUserDetail.findByUserName(userName);
        final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println(newPassword + " ||||  " + passwordEncoder.encode(currentUser.getPassword()));    
        if (passwordEncoder.matches(oldPassword, passwordEncoder.encode(currentUser.getPassword()))) {
             
            System.out.print("match");
            
        } else {
            System.out.print("not match");
        }
        return "redirect:/";
    }

the result is

pass ||||  $2a$10$Y3JMpBg/3l4SHJY/X8XRS.O3vLxr64iLLoLY3r933irwsnrvCIr2q
not match---------------

while i can login via the password "pass" which means the password is okey

SAR
  • 1,765
  • 3
  • 18
  • 42
  • Might be that one of them are too salty:P https://stackoverflow.com/questions/25844419/why-bcryptpasswordencoder-from-spring-generate-different-outputs-for-same-input – Siavash Renani Apr 11 '21 at 16:06

1 Answers1

0

You cannot match the new password with the old password encoded again. You can match the old password in the parameter with the current password.

You can try it like this:

if (passwordEncoder.matches(oldPassword, currentUser.getPassword())) {
    String encodedNewPassword = passwordEncoder.encode(newPassword);
    // Store encoded new password..
}

See also BCryptPasswordEncoder.matches(java.lang.CharSequence rawPassword, java.lang.String encodedPassword)

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
  • so how i can check if the password provide is same as old password in the database – SAR Apr 11 '21 at 17:17
  • Send user's current password to **matches** method after `oldPassword`. Example: `passwordEncoder.matches(oldPassword, currentUser.getPassword())` – İsmail Y. Apr 11 '21 at 20:44