@RequestMapping(value = "/account/changePassword", method = RequestMethod.POST)
public String submitChangePasswordPage(
@RequestParam("oldpassword") String oldPassword,
@RequestParam("password") String newPassword,
HttpServletRequest request) {
System.out.println("change password.............");
try{
jdbcUserDetailsManager.changePassword(oldPassword, newPassword);
}
catch( AuthenticationException e )
{
System.out.println( "Old password is incorrect!please rechange" );
//e.printStackTrace();
return "redirect:/account/change";
}
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = (User)auth.getPrincipal();
String userName = user.getUsername();
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, newPassword);
try {
token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager
.authenticate(token);
request.getSession();
SecurityContextHolder.getContext().setAuthentication(
authenticatedUser);
request.getSession()
.setAttribute(
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
SecurityContextHolder.getContext());
} catch (AuthenticationException e) {
System.out.println("Authentication failed: " + e.getMessage());
return "redirect:/account/change";
}
return "redirect:/";
}
public String submitChangePasswordPage(
@RequestParam("oldpassword") String oldPassword,
@RequestParam("password") String newPassword,
HttpServletRequest request) {
System.out.println("change password.............");
try{
jdbcUserDetailsManager.changePassword(oldPassword, newPassword);
}
catch( AuthenticationException e )
{
System.out.println( "Old password is incorrect!please rechange" );
//e.printStackTrace();
return "redirect:/account/change";
}
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = (User)auth.getPrincipal();
String userName = user.getUsername();
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, newPassword);
try {
token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager
.authenticate(token);
request.getSession();
SecurityContextHolder.getContext().setAuthentication(
authenticatedUser);
request.getSession()
.setAttribute(
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
SecurityContextHolder.getContext());
} catch (AuthenticationException e) {
System.out.println("Authentication failed: " + e.getMessage());
return "redirect:/account/change";
}
return "redirect:/";
}
本文展示了如何在Spring Security框架中实现修改密码的功能。当用户提交旧密码和新密码时,通过jdbcUserDetailsManager.changePassword方法检查旧密码并更新。如果旧密码不正确,会重定向到更改密码页面。验证新密码成功后,更新Security Context并重新认证用户。
1285

被折叠的 条评论
为什么被折叠?



