您不需要事先知道服务器列表,因为您可以设置Access-Control-Allow-Origin: *,但这并不安全,因为它允许其他站点使用您的服务。因此,请确保在构建标头时允许来自受限列表的 Access-Control-Allow-Origin。我只是使用正则表达式进行比较,因为我们允许来自多个。当我验证是否存在匹配时,我将请求来源返回到标头中。因此,如果我匹配web.*energydomain.com 之类的东西并且来源是webservices.energydomain.com,那么我会传回Access-Control-Allow-Origin: webservices.energydomain.com 这告诉调用服务(以及任何收听的人)我从这个来源接受并且只接受这个来源,即使我可能从 webstart.energydomain.com 接受。
所以我们使用 spring 创建了一个过滤器。
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
response.setHeader("Access-Control-Allow-Credentials", "true")
//If this is a pre-flight request, make sure that we are allowing them
if ("OPTIONS" == request.method) {
response.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS")
response.setHeader("Access-Control-Max-Age", "604800")
response.setHeader("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Origin, Vary, Cookie, Key")
//Check to see that the referrer/origin matches the set of allowed origins in the application configuration
String referrer = request.getHeader("Origin")
if (referrer?.matches(ServerProperties.instance.accessControlAllowOriginRegEx)) {
response.setHeader("Access-Control-Allow-Origin", referrer)
}
} else {
//set other headers here and continue chain (we don't bother continuing chain on preflight)
chain.doFilter(request, response)
}
}
您也可以在 htaccess 上执行此操作
<FilesMatch "\.(ttf|otf|eot|woff)$">
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(webservices.energydomain.com|webservicesmo.energydomain.com|webservicestest.energydomain.com)$" AccessControlAllowOrigin=$0
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
</IfModule>
</FilesMatch>
我更喜欢尝试减少飞行前的交通噪音并一起避免它们。特别是,我使用 xdomain。如果使用 Angular 或 jQuery,我的设置非常简单。在您的应用服务器上,按照以下链接的帮助中的说明添加 proxy.html。在您的“客户端”和中提琴上添加一些引用 js 文件的标签,不再进行预检。这包含在 iframe 中以避免需要进行 cors 检查。如上所述,您仍然可以像使用 CORS 预检一样控制原点,它只是一起避免了它们。
https://github.com/jpillora/xdomain