我正在尝试将 Spring Security (4.0.1) 与 AngularJS 集成。我能够使用基于 XML 的配置进行基本身份验证。问题是,每次用户输入无效凭据时,Web 浏览器都会显示弹出窗口。我尝试使用普通的 ServletFilters 以及使用基于 Spring 安全性的自定义过滤器来删除 WWW-Authenticate repsone 标头。还没有成功。有人可以帮我吗?
问问题
277 次
1 回答
0
扩展默认ExceptionTranslationFilter
为所有 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);
}
}
}
在默认之前添加AjaxExceptionTranslationFilter
到您的配置中FILTER_SECURITY_INTERCEPTOR
:
<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>
X-Requested-With
您需要在 Angular 应用程序中的 ajax 调用中添加 HTTP 标头拦截器,以便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);
}
};
}]);
}]);
于 2015-05-19T06:11:42.643 回答