检查每个node.js请求authentication凭证

我用Express和connect-auth来使用node.js来authentication用户。

这是请求/索引时的validation:

if(req.isAuthenticated()) { res.redirect('/dashboard'); } else { res.render('index', { layout: 'nonav' }); } 

但是,在注销并返回到fe'/ dashboard'后,我可以看到仪表板。

我怎样才能把validation检查到每一个请求,以确保有一个有效的用户在任何时候?

更新我没有任何authentication问题,一切工作正常! 我需要一个解决scheme,它检查每个路由/请求,如果有一个有效的用户,而不是在路由实现中放置一个函数或if语句,因为整个应用程序无论如何都需要一个有效的用户。 Express-Authentication-Example在路由定义中使用“restrict”,但是路由很多,很容易被遗忘。

 app.all('*',function(req,res,next){ if(req.isAuthenticated()){ next(); }else{ next(new Error(401)); // 401 Not Authorized } }); // NOTE: depending on your version of express, // you may need to use app.error here, rather // than app.use. app.use(function(err,req,res,next){ // Just basic, should be filled out to next() // or respond on all possible code paths if(err instanceof Error){ if(err.message === '401'){ res.render('error401'); } } }); 

如果你在需要authentication的路由之前和不需要路由的路由(例如主页,login等等)之前定义了all路由,那么它应该只影响需要它的路由。 或者,您可以使用RegExp而不是'*' ,其中包含需要validation的子path或path列表。

另一个select是创build一个函数,在每个需要auth的路由中包含:

 function IsAuthenticated(req,res,next){ if(req.isAuthenticated()){ next(); }else{ next(new Error(401)); } } app.get('/login',function(req,res,next){ res.render('login'); }); app.get('/dashboard',IsAuthenticated,function(req,res,next){ res.render('dashboard'); }); app.get('/settings',IsAuthenticated,function(req,res,next){ res.render('settings'); }); 

您可以使用connect提供的sessions机制。 把这段代码放在app.configure()来启用它:

  app.use(express.cookieParser()); app.use(express.session({ secret: 'some string used for calculating hash' })); 

之后,您将能够使用req.session对象(每个请求不同)来存储您的身份validation数据(或其他任何内容)。 所以,你的示例代码将如下所示:

 if (req.session && req.session.authorized) { res.redirect('/dashboard'); } else { res.render('index', {layout: 'nonav'}); } 

身份validation将如下所示:

 req.session.authorized = checkPassword(login, passw); 

登出:

 req.session.destroy(); 

更多信息可以在这里find。

另一种方法是app.use中间件function。 (在CoffeeScript中的例子)

 # middleware authKick = (req, res, next) -> if not do req.isAuthenticated then return res.redirect '/login' return do next # apply app.use authKick 

这将在每个请求上工作,而不必触摸路线。