spring security 密碼過期強制修改密碼


  • 定義認證失敗處理器處理CredentialsExpiredException密碼過期異常
public class AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public AuthenticationFailureHandler() {
        super("/login?error");
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException ex) throws IOException, ServletException {
        if (ex instanceof CredentialsExpiredException) {
        	// 保存異常信息到會話屬性,供頁面顯示
            saveException(req, ex);
            String userName = req.getParameter("username");
            // 跳轉到修改密碼頁面
            res.sendRedirect("/changepassword?error&username=" + userName);
        } else {
        	// 其他錯誤使用默認處理
            super.onAuthenticationFailure(req, res, ex);
        }
    }
}
  • 修改WebSecurity配置
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
	@Override
    protected void configure(HttpSecurity http) throws Exception {
    	...
    	http.formLogin().loginPage("/login")
    			// 注冊認證失敗處理器
                .failureHandler(new AuthenticationFailureHandler())
        ...
        http.authorizeRequests()
        		// 設置修改密碼端點無需授權訪問
                .antMatchers("/changepassword").permitAll()
    	...
    }
...
}
  • 定義修改密碼端點
@Controller
public class ChangePasswordController {
	@Autowired
	private UserService userService;
	// 修改密碼頁面
	@GetMapping("/changepassword")
	public ModelAndView changepassword(String username) {
		ModelAndView mv = new ModelAndView("changepassword");
		mv.getModel().put("username", username);
		return mv;
	}

	// 修改密碼
	@PostMapping("/changepassword")
	public void changepassword(String username, String oldPassword, String newPassword, HttpServletRequest request, HttpServletResponse res) throws IOException {
		try {
			userService.changePassword(username, oldPassword, newPassword);			
			// 修改成功跳轉到登陸頁面 
			request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new AuthenticationException("密碼修改成功,請重新登陸"));
			res.sendRedirect("/login");
		} catch (Exception e) {
			// 修改失敗返回錯誤信息
			request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, e);
			res.sendRedirect("/changepassword?error");
		}
	}
}
  • 定義修改密碼頁面
<!-- 顯示錯誤信息 -->
<div class="alert alert-danger" role="alert" th:text="${session.SPRING_SECURITY_LAST_EXCEPTION.getMessage()}" th:if="${session.SPRING_SECURITY_LAST_EXCEPTION!=null}"></div>
<!-- 修改密碼表單 -->
<form class="form-signin" method="post" action="/changepassword" onsubmit='return checkForm()'>
    <input type="text" id="username" name="username" class="form-control" placeholder="用戶名" required th:value="${username}">
    <input type="password" id="oldPassword" name="oldPassword" class="form-control" placeholder="原密碼" required>
    <input type="password" id="newPassword" name="newPassword" class="form-control" placeholder="新密碼" required>
    <button class="btn btn-lg btn-primary btn-block" type="submit">確認修改</button>
</form>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM