我看到当我对启用 CORS 的 Restify 服务执行 HTTP GET 时,默认情况下 access-control-allow-origin 标头设置为通配符。我宁愿它与我发送的 Origin 相呼应,因为这是每个OWASP的最佳实践。有什么建议我该怎么做?尝试了 API 文档中的默认标头、格式化程序等,但没有运气。
这就是我所做的:
var server = restify.createServer({
name: 'People Data Service',
version: '1.0.6'
});
server.pre(wrapper(restify.pre.pause()));
// Cleans up sloppy paths
server.pre(wrapper(restify.pre.sanitizePath()));
server.use(wrapper(restify.acceptParser(server.acceptable)));
server.use(wrapper(restify.authorizationParser()));
server.use(wrapper(restify.queryParser()));
server.use(wrapper(restify.bodyParser()));
server.use(wrapper(restify.CORS()));
// server.use(wrapper(restify.fullResponse()));
// Needed this for OPTIONS preflight request: https://github.com/mcavage/node-restify/issues/284
function unknownMethodHandler(req, res) {
if (req.method.toUpperCase() === 'OPTIONS') {
console.log('Received an options method request from: ' + req.headers.origin);
var allowHeaders = ['Accept', 'Accept-Version', 'Content-Type', 'Api-Version', 'Origin', 'X-Requested-With', 'Authorization'];
if (res.methods.indexOf('OPTIONS') === -1) {
res.methods.push('OPTIONS');
}
res.header('Access-Control-Allow-Credentials', false);
res.header('Access-Control-Expose-Headers', true);
res.header('Access-Control-Allow-Headers', allowHeaders.join(', '));
res.header('Access-Control-Allow-Methods', res.methods.join(', '));
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Max-Age', 1209600);
return res.send(204);
}
else {
return res.send(new restify.MethodNotAllowedError());
}
}
server.on('MethodNotAllowed', wrapper(unknownMethodHandler));