spring security jquery ajax重定向问题解决
服务器端security增加一个配置如下:
@Override protected void configure(HttpSecurity http) throws Exception { String loginPage = "/login"; http .exceptionHandling() .authenticationEntryPoint(new AjaxAuthenticationEntryPoint(loginPage)) .and() .addFilterBefore(new LocaleFilter(localeResolver), UsernamePasswordAuthenticationFilter.class) ... }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; import com.zhqn.sc.utils.CommonsUtils; public class AjaxAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint{ public AjaxAuthenticationEntryPoint(String loginFormUrl) { super(loginFormUrl); } @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { if (CommonsUtils.isAjax(request)) { String redirectUrl = buildRedirectUrlToLoginPage(request, response, authException); response.setHeader("redirectUrl", redirectUrl); response.sendError(HttpServletResponse.SC_FORBIDDEN); }else { super.commence(request, response, authException); } } }
客服端js设置:
$(document).ajaxError(function(event,xhr,options,exc){ if(xhr.status == 403 && xhr.getResponseHeader("redirectUrl")) { window.top.location.href = xhr.getResponseHeader("redirectUrl"); } });