引言
一般成功登录后,需要触发一些操作,比如我们经常收到你异地登录的消息等,都是登录成功后触发的事务。SpringSecurity框架涵盖这部分。
认证成功处理
OursAuthenticationSuccessHandler 实现 AuthenticationSuccessHandler接口,重写onAuthenticationSuccess方法。
@Component("oursAuthenticationSuccessHandler")
public class OursAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Object principal = authentication.getPrincipal();
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(new ObjectMapper().writeValueAsString(principal));
out.flush();
out.close();
}
}
OursAuthenticationFailureHandler、OursLogoutSuccessHandler、OursAuthenticationEntryPoint雷同,通过实现相应的接口,自定义处理行为。
配置
@Autowired
private AuthenticationSuccessHandler oursAuthenticationSuccessHandler;
@Autowired
private AuthenticationFailureHandler oursAuthenticationFailureHandler;
@Autowired
private LogoutSuccessHandler oursLogoutSuccessHandler;
@Autowired
private AuthenticationEntryPoint oursAuthenticationEntryPoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and().formLogin()
.loginPage("/login")
.defaultSuccessUrl("/index")
//登录成功
.successHandler(oursAuthenticationSuccessHandler)
//登录失败
.failureHandler(oursAuthenticationFailureHandler)
.permitAll()
.and().logout()
.logoutUrl("/logout")
//注销成功
.logoutSuccessHandler(oursLogoutSuccessHandler)
.permitAll()
.and().headers().frameOptions().sameOrigin()
.and().csrf().disable()
.exceptionHandling()
//未认证处理
.authenticationEntryPoint(oursAuthenticationEntryPoint)
;
}
以上代码将认证成功、认证失败、注销成功和未认证均做了体现。