我有一个在嵌入式Apache Tomcat(8.5.2)实例上运行的JAX-RS应用程序(RestEasy,3.1.2.Final)。这是一个公共REST服务,所以我在RestEasy中添加了一个CORS过滤器:
import org.jboss.resteasy.plugins.interceptors.CorsFilter;
@Override
public Set<Object> getSingletons() {
Set<Object> singletons = new LinkedHashSet<>();
// = = = CORS = = =
CorsFilter cors = getCorsFilter();
singletons.add(cors);
//...
return singletons;
}
private CorsFilter getCorsFilter() {
CorsFilter cors = new CorsFilter();
cors.getAllowedOrigins().add("*");
cors.setAllowCredentials(true);
cors.setAllowedMethods("GET,POST,PUT,DELETE,HEAD");
cors.setCorsMaxAge(1209600);
cors.setAllowedHeaders("Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,Accept-Encoding,Accept-Language,Access-Control-Request-Method,Cache-Control,Connection,Host,Referer,User-Agent");
return cors;
}
web.xml中还定义了一个安全约束:
<security-constraint>
<web-resource-collection>
<web-resource-name>Tango RESTful gateway</web-resource-name>
<url-pattern>/rest/*</url-pattern>
<http-method>GET</http-method>
<http-method>HEAD</http-method>
<http-method>POST</http-method>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>desy-user</role-name>
<role-name>mtango-rest</role-name>
</auth-constraint>
</security-constraint>
在这个设置中一切正常,但持续几周。几周后,CORS预检失败了401而不是正常序列:
请求:
Host: mstatus.esrf.fr
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Origin: https://ingvord.github.io
DNT: 1
Connection: keep-alive
响应:
Connection: Keep-Alive
Content-Length: 62
Content-Type: application/octet-stream
Date: Sun, 17 Sep 2017 07:28:19 GMT
Keep-Alive: timeout=5, max=85
Server: Apache-Coyote/1.1
显然,CORS过滤器不再执行 - 它设置的响应头没有。
这种行为可能是什么原因?重启后,它再次运行几周。
申请链接:https://ingvord.github.io/tango-controls.demo/
提前致谢,
答案 0 :(得分:0)
显然,web.xml中的以下额外配置似乎解决了这个问题:
<security-constraint>
<web-resource-collection>
<web-resource-name>CORS preflight</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>OPTIONS</http-method>
</web-resource-collection>
</security-constraint>
嗯,至少我们在相当长的一段时间内没有发现任何不当行为。