仅允许通过身份验证的用户访问受保护的页面 [英] Only allow passportjs authenticated users to visit protected page

查看:124
本文介绍了仅允许通过身份验证的用户访问受保护的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将此代码置于足以保护网页免受未经身份验证的用户的路径中吗?

Is placing this code inside of a route enough to protect pages from unauthenticated users?

if (!req.user) return res.send(401, "Not allowed in");


推荐答案

您可以使用 req。 isAuthenticated()检查请求是否经过身份验证。

You can use req.isAuthenticated() to check if the request is authenticated or not.

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}

app.get('/server', ensureAuthenticated, routes.server.get);
app.get('/login', routes.login.get);

或者像这样

app.all('*', function(req,res,next){
  if (req.path === '/' || req.path === '/login')
  next();
  else
  ensureAuthenticated(req,res,next);  
});

这篇关于仅允许通过身份验证的用户访问受保护的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆