Search code examples
node.jsoauth-2.0google-oauthpassport.js

Passport Get Refresh Token OAuth


How to get refresh token in OAuth strategy using Passport? I am able to get accesss token but need to get refresh token as well.

From Google Documentation, found that we need to add access_type=offline in request. How to achieve it using passport.

//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");
  }
);

Solution

  • You need to pass the access type as an argument when using 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',
      })
    );
    

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