基于快速JS路由的身份验证

时间:2015-07-13 10:36:50

标签: node.js express

我使用快速框架创建了node js app。

我已经创建了用于限制对某些路径的访问的中间件。

中间件实际上工作正常。但我在显示数据时遇到了困难。

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

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

我该如何处理这个案子????

2 个答案:

答案 0 :(得分:1)

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

在任何一种情况下,我都建议您从身份验证中分解凭证交换(也称为登录)。它们应该是单独的中间件功能。下面是一个示例。

虽然这回答了您的问题,特别是ExpressJS,但它确实遗漏了许多其他细节,这些细节在构建身份验证系统时很重要(比如如何安全地存储密码)。我在Stormpath工作,我们提供用户管理作为API,因此您不必担心所有安全细节!使用express-stormpath模块将API集成到您的应用程序中非常容易。您将在几分钟内拥有一个功能齐全的用户数据库,而无需设置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
  */
});

答案 1 :(得分:0)

您可以在应用中定位中间件。例如: -

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')