基于Express JS路由的身份validation

我已经使用快速框架创build节点js应用程序。

我已经创build了限制访问某些路由的中间件。

中间件实际上工作正常。 但是我在显示数据方面有困难。

假设在我的应用程序中,我创build了显示国家('/ country / master')列表的路线,即使用内部不同的/ defaultpath('/ country /')的html页面从mongoDB获取数据。

在这种情况下,用户将无法看到数据,因为我没有给“/”路由权限。 但我想显示数据,但不允许他使用“/”路线来检查数据。

我怎样才能处理这种情况?

答案取决于您的身份validation策略,即您使用会话标识符,访问令牌等

在这两种情况下,我都build议你从身份validation中打开证书交换(又名login)。 他们应该是独立的中间件function。 下面是这个样子的例子。

虽然这回答了ExpressJS的问题,但是在构build身份validation系统(比如如何安全地存储密码)方面,却遗漏了很多其他的细节。 我在Stormpath工作,我们提供用户pipe理作为一个API,所以你不必担心所有的安全细节! 使用express-stormpath模块将我们的API集成到您的应用程序中非常简单。 您将在几分钟内拥有全function的用户数据库,而无需设置mongo或用户表。

所有这一切,都是这样的例子:

 /* pseudo example of building your own authentication middleware */ function usernamePasswordExchange(req,res,next){ var username = req.body.username; var password = req.body.password; callToAuthService(username,password,function(err,user){ if(err){ next(err); // bad password, user doesn't exist, etc }else{ /* this part depends on your application. do you use sessions or access tokens? you need to send the user something that they can use for authentication on subsequent requests */ res.end(/* send something */); } }); } function authenticate(req,res,next){ /* read the cookie, access token, etc. verify that it is legit and then find the user that it's associated with */ validateRequestAndGetUser(req,function(err,user){ if(err){ next(err); // session expired, tampered, revoked }else{ req.user = user; next(); } }); } app.post('/login',usernamePasswordExchange); app.get('/protected-resource',authenticate,function(req,res,next){ /* If we are here we know the user is authenticated and we can know who the user is by referencing req.user */ }); 

你可以定位中间件在你的app.for例如: –

 app.get('/country/master',function(req,res){ }) app.use(function(req,res){ your middle ware for providing authentication }) // other routes where authentication should be enabled app.get('other urls')