node.js - 带有 passportjs + Vue 的 Google oAuth

标签 node.js express vue.js passport.js google-oauth

我目前无法在连接到我自己的 node express api 服务器的 vue 应用程序中处理 google oAuth 登录。

在 express api 服务器上,我使用 passport 作为处理 google oauth 的中间件,在通过 google 成功登录后,我在后端的回调中生成了一个 jwt。

passport.use(new GoogleStrategy({
    clientID: config.get('google.clientID'),
    clientSecret: config.get('google.clientSecret'),
    callbackURL: config.get('google.callbackUrl'),
  },
  function(accessToken, refreshToken, profile, done) {
    User.findOne(
      { socialID: profile.id },
      function (err, user) {
        if (err) {
            return done(err);
        }
        //No user was found... so create a new user with values from Facebook (all the profile. stuff)
        if (!user) {
          user = new User({
            name: profile.displayName,
            email: profile.emails[0].value,
            provider: profile.provider,
            socialID: profile.id,
          });
          user.save(function(err) {
            if (err) console.log(err);
          });
        }

        // the information which shall be inside the jsonwebtoken
        const payload = {
          user: {
            id: user.id
          }
        };

        // create jsonwebtoken and return it
        jwt.sign(
          payload,
          config.get('jwt.secret'), // get the secret from default.json to hash jsonwebtoken
          { expiresIn: config.get('jwt.lifetime') },
          (err, token) => {
            if(err) throw err; // if there is error, throw it and exit
            return done(JSON.stringify(token)); // return jwt token
          }
        );
      }
    );
  }
));

我的 api 服务器上有这些路由

// @route   GET api/auth/google
// @desc    Google auth route - get User From Google, store it if not exists yet
// @access  Public
router.get('/google',
  passport.authenticate('google', { scope: ['profile', 'email'], session: false })
);

// @route   GET api/auth/google/callback
// @desc    Google callback route
// @access  Public
router.get('/google/callback',
  passport.authenticate('google', { failureRedirect: '/', session: false }),
  function (req, res) {
    res.redirect('http://localhost:8080/?token=' + res);
  }
);

当我在/auth/google 调用我的后端 api 路由时,我成功地重定向到 google 登录页面。但是通过我的方法,我试图使用 get 参数“token”从回调 url 重定向回我的 vue 应用程序,以在前端接收 token 。我的后端回调路由中的重定向不起作用。如何将后端生成的 token 传递到前端?

最佳答案

我发现重定向不起作用,因为 return done() 函数需要两个参数才能正常工作。

我在 google passport 中间件内部更改了这样的 done 函数

jwt.sign(
 payload,
 config.get('jwt.secret'), // get the secret from default.json to hash jsonwebtoken
 { expiresIn: config.get('jwt.lifetime') },
  (err, token) => {
    if(err) throw err; // if there is error, throw it and exit
    return done(null, token); // return jwt token
  }
);

现在在我的 route ,我可以成功重定向并添加 token 作为获取参数 - 因此通过此解决方法,我收到了我的后端在前端生成的 jwt。

// @route   GET api/auth/google/callback
// @desc    Google callback route
// @access  Public
router.get('/google/callback',
  passport.authenticate('google', { failureRedirect: '/', session: false }),
  function (req, res) {
    let token = res.req.user;
    res.redirect('//localhost:8080/?token=' + token);
  }
);

关于node.js - 带有 passportjs + Vue 的 Google oAuth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60357072/

相关文章:

javascript - node.js 在异步请求中缺少发布数据

mysql - 如何防止nodejs中的sql注入(inject)和 Sequelize ?

node.js - Node : Hit endpoint that returns a CSV file and send the contents to client

javascript - 恢复属性键/值

javascript - 在 Javascript 中获取数组中对象的名称

javascript - 如何使用 mongoskin 指定单独的用户名和密码参数?

node.js - 无法通过express.js和路径在views目录中查找 View

javascript - Vuejs 路由导航守卫异步身份验证状态请求

vue.js - 扩展 Vue 生命周期钩子(Hook)

javascript - 重启 Vue 过渡