2015-07-13 56 views
1

我已经创建了使用快速框架的节点js应用程序。基于快速JS路由的身份验证

我创建了中间件来限制对某些路线的访问。

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

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

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

我该如何处理这种情况?

+0

你是什么化妆用的是什么意思?如果你的意思是你想禁止某人发布数据,那么你只能使用中间件进行发布。 like ...'app.post('/',yourRestrictionFunction)' – Pravin

回答

1

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

在这两种情况下,我建议你打破认证中的凭证交换(aka登录)。它们应该是单独的中间件功能。下面是这个样子的例子。

虽然这回答了您的问题,特定于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 
    */ 
}); 
0

你可以在你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') 
+0

我有路由“/ country/master”,这是我的html视图,“/ country /”是默认的api获取数据。这是我的应用程序获取数据所需的,我需要当用户试图击中浏览器上面的网址时,他应该受到限制 – Overseas634

+0

@ Overseas634你试图说/ country/master是路由,它给出了html页面作为响应。 – KlwntSingh

+0

yes'/ country/master'是给出html页面作为回应的路由 – Overseas634