如何防止无特权访问rest的APIurl?

这是一个关于node.js和restful api的问题。

我用mongoose.Schema创build了一个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数据列表。 如果我在真实的服务器上运行testing,那意味着访问url的任何人都可以看到数据。

我怎样才能真正隐藏其他用户的数据?

如果你的标准只是一个特定的用户可以访问它,或者只有签名的用户才能访问它,那么你可以使用像下面这样的帮助函数来完成它。

 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) }; 

以前的答案肯定会适用于单个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) {...}); 

或者你甚至可以在jsonconfiguration文件中声明所有的授权path:

 app.use(cansec.validate); app.use(cansec.authorizer('./route-security.json')); 

然后你的configuration:

 { "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"] ] }