javascript - 如何判断用户何时登录 | express | Passport | Node

标签 javascript node.js express authentication passport.js

我为自己构建了一个快速后端 API(端口 3000)和端口(8080)上的 Vue.js 前端,我在后端服务器上实现了 Passport 身份验证登录系统。如果我访问 localhost:3000/auth/google,登录系统就会正常工作,并且我会在我的 mongoose 数据库中获得一个 google-ID。

我的服务器上有这段代码,成功登录后会重定向到我的前端,但我现在如何知道用户已登录我的 Vue.js 前端?

app.get(
  '/auth/google',
  passport.authenticate('google', {
    scope: ['profile']
  })
);

app.get(
  '/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('http://localhost:8080/profile');
  }
);

我的 Passport 配置是这样设置的

passport.serializeUser((user, done) => {
  done(null, user);
});

passport.deserializeUser((id, done) => {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

module.exports = function(passport, GoogleStrategy) {
  passport.use(
    new GoogleStrategy(
      {
        clientID: process.env.GOOGLE_CLIENT_ID,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        callbackURL: 'http://localhost:3000/auth/google/callback'
      },
      function(token, tokenSecret, profile, done) {
        var query = { googleId: profile.id };
        var update = {
          $set: {
            googleId: profile.id
          }
        };
        var options = { new: true, upsert: true };
        User.findOneAndUpdate(query, update, options, function(err, u) {
          return done(err, u);
        });
      }
    )
  );
};````

最佳答案

您可以生成一个jsonwebtoken并将其设置在response对象的cookie中

app.get(
  '/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {
    let token = jwt.sign({
       exp: Math.floor(Date.now() / 1000) + (60 * 60),
       user: req.user //if you have user here
       }, 'secret');
    res.cookie("token", token, {httpOnly:false})
    res.redirect('http://localhost:8080/profile');
  }
);

在 Vue 中,您可以使用像 vue-cookies 这样的包来获取 cookie $cookies.get('token')

关于javascript - 如何判断用户何时登录 | express | Passport | Node ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59860930/

相关文章:

javascript - 在 Angular JS 中打开特定列表

javascript - Node.JS 作业/后台进程和高可用性

node.js - 使用vuejs和nodejs从mongodb数据库读取数据

javascript - Service Worker 注册错误 : Unsupported MIME type ('text/html' )

带有 vhost 的 Node.js/Express 与 Sails.js 框架应用程序冲突

javascript - Excel 表格中的 Protractor 测试结果

javascript - 如何将数组值放入嵌套数组中

javascript - vanilla js,获取具有特定属性的 anchor

node.js - 使用 app.js 或 'npm start' 启动 Express.js?

使用 Webpack 的 Javascript 模块