我发现每当我对启用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));
答案 0 :(得分:0)
我在我的restify基础应用程序上这样做:
//setup cors
restify.CORS.ALLOW_HEADERS.push('accept');
restify.CORS.ALLOW_HEADERS.push('sid');
restify.CORS.ALLOW_HEADERS.push('lang');
restify.CORS.ALLOW_HEADERS.push('origin');
restify.CORS.ALLOW_HEADERS.push('withcredentials');
restify.CORS.ALLOW_HEADERS.push('x-requested-with');
server.use(restify.CORS());
你需要使用restify.CORS.ALLOW_HEADERS.push方法来推送你想要首先解析的头,然后使用CORS中间件来启动CORS功能。
答案 1 :(得分:0)
我找到了一种方法,通过对Restify中的cors.js文件进行简单修改,如下所示:
Index: node_modules/restify/lib/plugins/cors.js
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- node_modules/restify/lib/plugins/cors.js (revision )
+++ node_modules/restify/lib/plugins/cors.js (revision )
@@ -102,6 +102,7 @@
res.setHeader(AC_ALLOW_ORIGIN, origin);
res.setHeader(AC_ALLOW_CREDS, 'true');
} else {
+ origin = req.headers['origin'];
res.setHeader(AC_ALLOW_ORIGIN, origin);
}
即使将凭据设置为false,这也会将原点添加到响应标头中。此外,如果您想将您的来源列入白名单,只需将其添加到您的配置中:
server.use(restify.CORS({'origins': ['http://localhost', 'https://domain.my.com', 'https://anotherDomain.my.com']}));