护照获取刷新令牌OAuth

时间:2020-10-02 18:16:12

标签: node.js oauth-2.0 google-oauth passport.js

如何使用Passport在OAuth策略中获取刷新令牌?我能够获取访问令牌,但也需要获取刷新令牌。

从Google文档中发现,我们需要在请求中添加 access_type = offline 。 如何使用护照来实现。

//STRATEGY
passport.use(
  new GoogleStrategy(
    {
      clientID: googleKeys.clientID,
      clientSecret: googleKeys.clientSecret,
      callbackURL: urls.cb,
    },
    (accessToken: any, refreshToken: any, profile: any, cb: any) => {

      //refreshToken is undefined
      cb(null, { email: profile._json.email });

    }
  )
);

router.get(
  "/auth/google",
  passport.authenticate("google", {
    scope: [
      "https://www.googleapis.com/auth/userinfo.profile",
      "https://www.googleapis.com/auth/userinfo.email",
    ],
  })
);

//REDIRECT URI
router.get(
  "/auth/google/callback",
  passport.authenticate("google", { failureRedirect: "/", session: false }),
  (req: Request, res: Response) => {
    res.send("Success");
  }
);

1 个答案:

答案 0 :(得分:1)

使用passport.authenticate时,您需要将访问类型作为参数传递。

router.get(
  "/auth/google",
  passport.authenticate("google", {
    scope: [
      "https://www.googleapis.com/auth/userinfo.profile",
      "https://www.googleapis.com/auth/userinfo.email",
    ],
    accessType: 'offline',
    prompt: 'consent',
  })
);

参考:https://github.com/jaredhanson/passport-google-oauth2/issues/4#issuecomment-344460414