1、编写自己的SuccessHandler
public class AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth)
throws IOException, ServletException {
String ajaxHeader = ((HttpServletRequest) request).getHeader("X-Requested-With");
boolean isAjax = "XMLHttpRequest".equals(ajaxHeader);
if (isAjax) {
String principal = auth.getPrincipal().toString();
JSONObject returnObj = new JSONObject();
returnObj.put("status", "1");
returnObj.put("data", principal);
response.getWriter().print(returnObj.toString());
response.getWriter().flush();
} else {
super.onAuthenticationSuccess(request, response, auth);
}
}
}
2、注册Bean
/**
* 登陆成功
* @return
*/
@Bean
public SimpleUrlAuthenticationSuccessHandler authenticationSuccessHandler() {
AuthenticationSuccessHandler authenticationSuccessHandler = new AuthenticationSuccessHandler();
return authenticationSuccessHandler;
}
3、配置
@Override
public void configure(HttpSecurity http) throws Exception {
http.headers()
.addHeaderWriter(
new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))
.and().csrf().disable().formLogin().successHandler(authenticationSuccessHandler())
.failureHandler(authenticationFailureHandler())
.loginProcessingUrl("/login")
.loginPage("/index.html").permitAll()
.and().logout().logoutSuccessHandler(authenticationLogoutSuccessHandler())
.deleteCookies("JSESSIONID").invalidateHttpSession(true) // 设置退出,invalidateHttpSession设置退出后无效session
.and().authorizeRequests().anyRequest().authenticated()
.and().exceptionHandling().authenticationEntryPoint(new AjaxAwareAuthenticationEntryPoint("/index.html"))
.and().sessionManagement().invalidSessionUrl("/timeout").maximumSessions(1).maxSessionsPreventsLogin(false)
.expiredUrl("/timeout");
}