我在Spring应用程序中有一个CORS过滤器,如here所述。当我通过邮递员向API发出请求时(对于经过身份验证,未经身份验证和OAuth2令牌请求),一切正常并且标题已添加。
但是,通过angular的OAuth2令牌请求不起作用 - 请求甚至从未进入CorsFilter。奇怪的是,经过身份验证和未经身份验证的请求都可以正常工作(并通过CorsFilter)。
这是给我带来麻烦的角度部分:
headers = credentials ? {
Authorization : "Basic " + btoa(credentials.username + ":" + credentials.password)
} : {};
$http.post('http://localhost:8080/api/oauth/token?grant_type=client_credentials', {}, {headers: headers})
.success(function (tokenResponse) {
... stuff ...
callback && callback(true);
})
.error( function() {
... stuff ...
callback && callback(false);
});
这是来自js控制台的错误:
X OPTIONS http://localhost:8080/api/oauth/token?grant_type=client_credentials
X XMLHttpRequest cannot load http://localhost:8080/api/oauth/token?grant_type=client_credentials.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8079' is therefore not allowed access.
The response had HTTP status code 401.
为什么Angular的表现与postman不同?
此外,为了完整起见,我将包括CorsFilter(虽然有问题的请求甚至没有在这里提出)并且它的配置:
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "http://localhost:8079");//https://web.fama.io/");
if (request.getMethod() != null && request.getMethod().equals("OPTIONS")) {
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
String allowed = String.join(",", Collections.list(request.getHeaders("Access-Control-Request-Headers")));
response.addHeader("Access-Control-Allow-Headers", allowed);
}
filterChain.doFilter(request, response);
}
}
为清楚起见,我的Web服务器在端口8079上,而我的api服务器在端口8080上。我正在尝试允许端口8079和端口8080之间的CORS请求。