1. 程式人生 > >spring boot security 實現登陸時ajax請求返回json,而不是直接頁面跳轉

spring boot security 實現登陸時ajax請求返回json,而不是直接頁面跳轉

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");
}