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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM