I implement a method inside my update method for check if the given password in a UpdateForm is matching with an encoded password from db.
I didn't found any tutorial or solution already but I've tried some stuff but nothing work.
This is my update method
@RequestMapping(value = {"/home/editUser"}, method = RequestMethod.POST)
public String home(@ModelAttribute("editUser") User editUser, Model model) {
logger.info("/home/editUser");
try {
User user = userService.findById(editUser.getId());
if (!user.equals(editUser)) {
//old password matching
if (user.getPassword_1() == editUser.getPassword_1()) {
//encode new password
editUser.setPassword(PassEncoding.getInstance().passwordEncoder.encode(editUser.getPassword()));
//update
userService.update(editUser);
model.addAttribute("msg", "success");
}
else {
System.out.println("not match");
}
} else {
model.addAttribute("msg", "same");
}
} catch (Exception e) {
model.addAttribute("msg", "fail");
logger.error("editUser: " + e.getMessage());
}
model.addAttribute("home", editUser);
return "home";
}
Password_1
is my oldpassword (actual) , but I don't know how I can implement the password encoder and it gives
not match
Thanks in advance for help :)
I've just tried
if(PassEncoding.getInstance().passwordEncoder.matches(editUser.getPassword_1(), user.getPassword_1()))
but it gives
not match
It's work with
if(PassEncoding.getInstance().passwordEncoder.matches(editUser.getPassword_1(), user.getPassword()))
Thanks a lot !
you can use org.springframework.security.crypto.password.PasswordEncoder
@Autowired
private final PasswordEncoder passwordEncoder;
....
....
boolean result = passwordEncoder.matches(password_plan_text_here, encoded_password_here);
refer below link for more info https://docs.spring.io/spring-security/site/docs/4.2.4.RELEASE/apidocs/org/springframework/security/crypto/password/PasswordEncoder.html
You need to choose correct encoder as below.
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
You can implement this like bellow
If you want, You can use this annotation in controller argument to make sure your user is authenticated.
@AuthenticationPrincipal User user
.........
.........
Use this method like structure to check your password is matched or not. It return true value if it is matched.
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
..........
..........
Your input password is "password" that you make to match with DB user find by
User user = userService.findById(editUser.getId());
public boolean userPasswordCheck(String password, User user) {
PasswordEncoder passencoder = new BCryptPasswordEncoder();
String encodedPassword = user.getPassword();
return passencoder.matches(password, encodedPassword);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With