Spring 安全 (4.0.1) 与 AngularJS 集成。每次用户输入无效凭据时获取基本身份验证弹出窗口

Spring Security (4.0.1) Integration with AngularJS. Getting Basic Authentication Popup every time user enters invalid credentials

我正在尝试将 Spring 安全性 (4.0.1) 与 AngularJS 集成。我可以使用基于 XML 的配置进行基本身份验证。问题是,每次用户输入无效凭据时,Web 浏览器都会弹出。我尝试使用普通 ServletFilters 以及使用 Spring 基于安全的自定义过滤器来删除 WWW-Authenticate repsone header。还没有成功。有人可以帮我解决这个问题吗?

扩展默认值 ExceptionTranslationFilter returns 所有 ajax 请求的 HTTP 401 而不是基本身份验证质询:

package mypackage;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.ExceptionTranslationFilter;

public class AjaxExceptionTranslationFilter extends ExceptionTranslationFilter {

    @Autowired
    public AjaxExceptionTranslationFilter(AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationEntryPoint);
    }

    @Override
    protected void sendStartAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException reason)
            throws ServletException, IOException {
        boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

        if (isAjax) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
        } else {
            super.sendStartAuthentication(request, response, chain, reason);
        }
    }
}

在默认 FILTER_SECURITY_INTERCEPTOR 之前将 AjaxExceptionTranslationFilter 添加到您的配置中:

<security:http pattern="/**">
    <security:custom-filter before="FILTER_SECURITY_INTERCEPTOR" ref="exceptionTranslationFilter"/>
    <!-- ... -->
</security:http>

<bean id="exceptionTranslationFilter" class="mypackage.AjaxExceptionTranslationFilter">
    <constructor-arg ref="loginUrlAuthenticationEntryPoint"/>
</bean>

您需要在 angular 应用程序的 ajax 调用中为 HTTP header X-Requested-With 添加一个拦截器,以触发 AjaxExceptionTranslationFilter在后端。

此外,您应该从后端捕获 HTTP 401 响应并进行相应处理。

$httpProvider.interceptors.push(['$q', function($q) {
    return {
        'responseError': function(rejection) {
            if(rejection.status === 401) {
                // .. do something meaningful
            }


            return $q.reject(rejection);
        }
    };
}]);

$httpProvider.interceptors.push(['$q', function ($q) {
    return {
        'request': function (config) {
            config.headers["X-Requested-With"] = "XMLHttpRequest";
            return config || $q.when(config);
        }
    };
}]);

}]);