上一个回答中,请如果用户有初始密码,那么该如何改逻辑
时间: 2024-03-08 21:49:21 浏览: 21
如果用户有初始密码,那么你需要在用户登录时对用户输入的密码先进行判断,如果是初始密码,则提示用户需要修改密码,并跳转到修改密码的页面。具体实现可以参考下面的示例代码:
```
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api-docs/**").permitAll()
.antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/change-password").authenticated() // 需要身份认证才能访问修改密码的页面
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().logoutSuccessUrl("/login").permitAll()
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler()) // 处理访问拒绝的异常
.and()
.headers().frameOptions().disable(); // 允许在iframe中显示swagger-ui
}
// 自定义访问拒绝的处理器,跳转到修改密码的页面
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return new AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
if (accessDeniedException instanceof CredentialsExpiredException) {
response.sendRedirect(request.getContextPath() + "/change-password");
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
}
}
};
}
```
在上面的代码中,我们首先通过configure()方法配置了用户认证的逻辑,然后在configure()方法中配置了HttpSecurity对象,设置了各种访问规则和安全选项,其中包括需要身份认证才能访问修改密码的页面。同时,我们还通过accessDeniedHandler()方法自定义了访问拒绝的处理器,在用户身份过期时跳转到修改密码的页面。
接下来是修改密码的Controller代码示例:
```
@Autowired
private UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
@GetMapping("/change-password")
public String showChangePasswordPage() {
return "change-password";
}
@PostMapping("/change-password")
public String changePassword(@RequestParam("oldPassword") String oldPassword,
@RequestParam("newPassword") String newPassword,
Principal principal) {
User user = userService.getUserByPhoneNumber(principal.getName());
if (passwordEncoder.matches(oldPassword, user.getPassword())) {
String encodedPassword = passwordEncoder.encode(newPassword);
user.setPassword(encodedPassword);
userService.updateUser(user);
return "redirect:/home";
} else {
return "redirect:/change-password?error";
}
}
```
在上面的代码中,我们首先通过@GetMapping注解定义了一个GET请求的Controller方法,用于显示修改密码的页面;然后通过@PostMapping注解定义了一个POST请求的Controller方法,用于处理用户提交的修改密码的表单。在处理表单时,我们首先通过Principal对象获取当前登录用户的用户名(即手机号),然后根据手机号查询出对应的User对象,并使用PasswordEncoder对用户输入的旧密码进行解密,然后与User对象中存储的密码进行比对。如果旧密码匹配,则使用PasswordEncoder对新密码进行加密,并将加密后的密码存储到User对象中,最后调用UserService的updateUser()方法更新用户信息,并跳转到首页。如果旧密码不匹配,则跳转回修改密码的页面,并显示错误信息。