这是一个关于node.js和restful api的问题。
我用mongoose.Schema创建了一个ProductModel,这是读取产品列表的路径。
app.get('/api/products', function (req, res) {
ProductModel.find(function (err, products) {
if (!err)
res.json(products);
else
console.log(err);
});
});当我在本地服务器上运行这个应用程序并访问url *:3000/api/products时,我可以看到json数据的列表。如果我在真实的服务器上运行测试,这意味着访问url的任何人也可以看到数据。
我如何才能真正对其他用户隐藏数据?
发布于 2014-12-27 23:58:25
如果您的条件是只有一个特定的用户可以访问它,或者只有签名的用户才能访问它,那么您可以使用如下所示的helper函数来实现。
app.get('/api/products', check_user, function(req, res) {
ProductModel.find(function(err, products) {
if (!err)
res.json(products);
else
console.log(err);
});
});
function check_user(req, res, next) {
//if you are using sessions then you can get the current user with req.user
if (req.user != 'xyz') return res.json('message': 'you dont have permissions to access this url');
next(); //if it is xyz then call the next() iterator function that will take u to the final callback(productFind)
};发布于 2014-12-29 14:14:46
前面的答案肯定适用于单个URL或简单用户。如果你正在做一个拥有大量用户和不同授权级别的完整应用程序,你需要一个安全框架。
我是cansecurity https://github.com/deitch/cansecurity的作者。
使用cansecurity,您可以通过编程方式完成此操作:
cs = require('cansecurity');
app.use(cansec.validate);
app.get('/api/products', cansec.restrictToLoggedIn, function(req, res) {...});
// or lots of other built in authorization restrictions
app.get('/api/products', cansec.restrictToRoles("admin"), function(req, res) {...});
app.get('/api/products', cansec.restrictToSelf, function(req, res) {...});或者,您甚至可以在json配置文件中声明所有授权路径:
app.use(cansec.validate);
app.use(cansec.authorizer('./route-security.json'));然后是你的配置:
{
"routes": [
// [verb,path,default,[test params,] test condition]
["GET","/api/products",true,"user === 'xyz'"],
// and lots of other options
["GET","/api/user/:user","user.roles.admin === true || user.id === req.param('user')"],
["GET","/api/user/:user",{"private":"true"},"user.roles.admin === true || user.id === req.param('user')"],
["PUT","/api/user/:user","user.roles.admin === true || user.id === req.param('user')"],
["GET","/api/user/:user/roles","user.roles.admin === true || user.id === req.param('user')"],
["PUT","/api/user/:user/roles","user.roles.admin === true"]
]
}https://stackoverflow.com/questions/27667483
复制相似问题