认证成功的处理
登录成功后,如果除了跳转页面还需要执行一些自定义代码时,如:统计访问量,推送消息等操作时,可以自定义登录成功处理器。
自定义登录成功处理器
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
UserDetails userDetails = (UserDetails)authentication.getPrincipal();
System.out.println("用户名:" + userDetails.getUsername());
System.out.println("其他信息");
response.sendRedirect("/main");
}
}
配置登录成功处理器
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login.html")
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/login")
.successHandler(new LoginSuccessHandler())
.failureForwardUrl("/fail");
测试
认证失败的处理
登录失败后,如果除了跳转页面还需要执行一些自定义代码时,如:统计失败次数,记录日志等,可以自定义登录失败处理器。
自定义登录失败处理器
public class LoginFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
System.out.println("记录失败日志。。。。");
response.sendRedirect("/fail");
}
}
配置登录失败处理器
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login.html")
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/login")
.successHandler(new LoginSuccessHandler())
.failureHandler(new LoginFailureHandler());
http.authorizeRequests()
.antMatchers("/login.html").permitAll()
.antMatchers("/fail").permitAll()
.anyRequest().authenticated();
测试
|