【发布时间】:2017-02-25 19:50:31
【问题描述】:
我已通过以下方式在我的 grails 3 应用程序中允许 cors:
cors:
enabled: true
并添加了过滤器:
public CorsFilter() { }
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
throws ServletException, IOException {
String origin = req.getHeader("Origin");
boolean options = "OPTIONS".equals(req.getMethod());
if (options) {
if (origin == null) return;
resp.addHeader("Access-Control-Allow-Headers", "origin, authorization, accept, content-type, x-requested-with");
resp.addHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");
resp.addHeader("Access-Control-Max-Age", "3600");
}
resp.addHeader("Access-Control-Allow-Origin", origin == null ? "*" : origin);
resp.addHeader("Access-Control-Allow-Credentials", "true");
if (!options) chain.doFilter(req, resp);
}
问题是请求正确响应, 但如果请求具有标头“Origin”,则请求返回 403
即使响应头是:
Access-Control-Allow-Credentials →true
Access-Control-Allow-Origin →http://localhost:4200
Cache-Control →no-store, no-cache, must-revalidate, max-age=0
Content-Length →0
Date →Sat, 25 Feb 2017 19:44:21 GMT
X-Application-Context →application:development
知道如何解决这个问题吗?
谢谢
【问题讨论】:
-
你在使用 spring security 吗?
-
不,这是一个完全没有安全保障的项目。不过是个rest profile,不知道这个profile有没有什么特别之处
-
为什么要注册自己的过滤器? grails.cors.enabled=true 为你注册一个过滤器
-
我在没有过滤器的情况下尝试过,我遇到了同样的错误。这就是为什么我认为我也应该添加它
-
我应该注意到过滤器实际上正在工作,因为在响应标头中我得到
Access-Control-Allow-Origin,但如果我从请求中删除标头“Origin”,我仍然得到 403,它有效