Google护照oauth并交换访问令牌的授权码

时间:2020-06-23 03:10:06

标签: node.js express oauth-2.0 passport.js mern

我是全栈开发的新手,并且花了很多时间研究并尝试实施针对我的问题的解决方案。

我能够使用护照成功地实现身份验证,现在正试图了解如何与访问令牌交换我返回的身份验证代码,以便进行身份验证的用户可以从我的应用程序访问其电子邮件。

Passport.js文件:

const GoogleStrategy = require("passport-google-oauth20").Strategy;
const mongoose = require("mongoose");
const keys = require("../config/keys");

const User = mongoose.model("users");

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

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


passport.use(
  new GoogleStrategy(
    {
      clientID: keys.googleClientID,
      clientSecret: keys.googleClientSecret,
      callbackURL: "/auth/google/callback", //route user is sent to after granting permission to app
    },
    async (accessToken, refreshToken, profile, done) => {
      const existingUser = await User.findOne({ googleId: profile.id });
      if (existingUser) {
        return done(null, existingUser); //if we add a return here, we don't need the else statement
      }

      const user = await new User({
        googleId: profile.id,
        fullname: profile.name.givenName + " " + profile.name.familyName,
        firstname: profile.name.givenName,
        lastname: profile.name.familyName,
       
      }).save();

      done(null, user);
    }
  )
);

authRoutes.js文件:

const mongoose = require("mongoose");
const User = mongoose.model("users");


module.exports = (app) => {
  app.get(
    "/auth/google",
    passport.authenticate("google", {
      scope: [
        "https://www.googleapis.com/auth/gmail.readonly",
        "profile",
        "email",
      ],
    })
  );

  //turns code returned from google into an actual profile
  app.get(
    "/auth/google/callback",
    passport.authenticate("google"),
    async (req, res) => {
    
      const gCode = req._parsedUrl.search;

      res.redirect("/targets" + gCode);
    }
  );

  app.get("/api/logout", (req, res) => {
    req.logout();
    res.redirect("/");
  });

  //this tells us whether user is logged in or not
  app.get("/api/current_user", (req, res) => {
    res.send(req.user);
  });
};

作为一个没有经验的开发人员,我不确定我是否会犯错。但是,到目前为止,我可以使用上面的代码成功登录和注销。我的想法是,使用从const gCode = req._parsedUrl.search获得的“代码”值,我将能够将代码转换为访问令牌,然后将其用于向Google发出请求,以允许用户查看自己的电子邮件该应用程序。请问我如何将我从authRoutes.js的const gCode = req._parsedUrl.search中获得的代码值转换为访问令牌?我已经阅读了几次文档,但是无法完全理解。

预先感谢

0 个答案:

没有答案