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