且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 node.js 中实现登录身份验证

更新时间:2023-11-30 21:50:16

这是我如何使用 Express.js一个>:

1) 检查用户是否已通过身份验证:我有一个名为 CheckAuth 的中间件函数,我在每条需要对用户进行身份验证的路由上使用它:

1) Check if the user is authenticated: I have a middleware function named CheckAuth which I use on every route that needs the user to be authenticated:

function checkAuth(req, res, next) {
  if (!req.session.user_id) {
    res.send('You are not authorized to view this page');
  } else {
    next();
  }
}

我在我的路线中使用这个功能是这样的:

I use this function in my routes like this:

app.get('/my_secret_page', checkAuth, function (req, res) {
  res.send('if you are viewing this page it means you are logged in');
});

2) 登录路径:

app.post('/login', function (req, res) {
  var post = req.body;
  if (post.user === 'john' && post.password === 'johnspassword') {
    req.session.user_id = johns_user_id_here;
    res.redirect('/my_secret_page');
  } else {
    res.send('Bad user/pass');
  }
});

3) 注销路径:

app.get('/logout', function (req, res) {
  delete req.session.user_id;
  res.redirect('/login');
});      

如果您想了解有关 Express.js 的更多信息,请在此处查看他们的网站:expressjs.com/en/guide/routing.html如果需要更复杂的东西,请查看 everyauth(它有很多可用的身份验证方法,用于 facebook、twitter 等;很好的教程关于它这里).

If you want to learn more about Express.js check their site here: expressjs.com/en/guide/routing.html If there's need for more complex stuff, checkout everyauth (it has a lot of auth methods available, for facebook, twitter etc; good tutorial on it here).