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

1

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

so how i can check if the password provide is same as old password in the database
Send user's current password to matches method after oldPassword. Example: passwordEncoder.matches(oldPassword, currentUser.getPassword())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.