使用security框架后如何修改用户密码
//加解密方法
BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
修改密码要求输入原密码password(未加密),paaword2为数据库取出的该用户加密后的密码,对两者进行对比。
//输入密码与数据库密码比较
boolean matches = bc.matches(password,password2 );
全部代码
@RequestMapping("/updatePassword")
public String updatePassword(HttpServletRequest request) {
//获取session
HttpSession session = request.getSession();
//获取session域的用户名
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
User user = (User) authentication.getPrincipal();
System.out.println(user);
String username = user.getUsername();
//获取用户输入的原密码
String password = request.getParameter("password");
//用户输入的新密码
String newPassword = request.getParameter("newPassword");
//根据名字获得用户
SysUser sysUser = sysUserService.findByName(username);
//获得用户加密后的原密码
String password2 = sysUser.getPassword();
//判断输入的原密码和加密后的密码是否一致
BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
boolean matches = bc.matches(password,password2 );
if (matches) {
sysUser.setPassword(passwordEncoder.encode(newPassword));
//如果输入原密码正确就修改密码
sysUserService.updatePassword(sysUser);
session.setAttribute("result","true");
return "main";
} else {
//如果不存在提示密码不正确
session.setAttribute("result","false");
}
return "update-password";
}
原文链接:https://blog.csdn.net/Mr_LiYyang/article/details/97312327