spring security ajax 跳转登录页

来源:互联网 发布:衣柜要做到顶吗 知乎 编辑:程序博客网 时间:2024/05/18 03:44

对于 ajax 无法捕获302的原理参考


http://www.cnblogs.com/dudu/p/ajax_302_found.html


大体流程为

ajax -> browser -> server -> 302 -> browser(redirect) -> server -> browser -> ajax callback

结论 

如果你想在ajax请求中根据302响应通过location.href进行重定向是不可行的。


下面进行解决方案

1.新增

public class AjaxAwareLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
    public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
           response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");//对于ajax请求不重定向  而是返回错误代码
        } else {
            super.commence(request, response, authException);
        }
    }
}

2.配置 springSecurity

<beans:bean id="authEntryPoint" class="org.springframework.web.filter.AjaxAwareLoginUrlAuthenticationEntryPoint" scope="singleton">
    <beans:property name="loginFormUrl" value="/login.html" />
</beans:bean>

<http auto-config="true"  entry-point-ref="authEntryPoint">

……

3.前台页面

$(document).ready(function(){
$.ajaxSetup({
complete: function(xmlHttp) {
if(xmlHttp.status==403){
                  location.href=  //跳转到登陆页面

                      }

                  }
   });
});


0 0
原创粉丝点击