在 Node 中通过 Google 身份验证来获取刷新令牌

问题描述 投票:0回答:1

我尝试获取refreshToken,因为accessToken每次使用需要几分钟的时间。 在代码中我无法获取。我的错误是什么?

import * as passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
...
passport.use(
      new GoogleStrategy(
        {
          clientID: this.configService.get("GOOGLE_CLIENT_ID"),
          clientSecret: this.configService.get("GOOGLE_SECRET"),
          callbackURL: "http://localhost:3000/schedule/google/callback",
          scope: [
            "https://www.googleapis.com/auth/calendar.events",
            "profile",
            "email",
            "https://www.googleapis.com/auth/calendar",
            "https://www.googleapis.com/auth/userinfo.profile",
            "https://www.googleapis.com/auth/userinfo.email",
          ],
          accessType: "offline",
          prompt: "consent",
          // passReqToCallback: true
        },
        function (accessToken, refreshToken, profile, done) {
          console.log(refreshToken);
          return done(null, accessToken);
        }
      )
    );
node.js passport.js
1个回答
0
投票

在策略创建期间传递范围无效。请参阅Passport Google Oauth20 文档

不要在策略创建期间传递范围、访问类型和提示,而是在身份验证请求期间传递。

你可以这样做:

第一步:配置策略

passport.use(
      new GoogleStrategy(
        {
          clientID: this.configService.get("GOOGLE_CLIENT_ID"),
          clientSecret: this.configService.get("GOOGLE_SECRET"),
          callbackURL: "http://localhost:3000/schedule/google/callback",
        },
        function (accessToken, refreshToken, profile, done) {
          console.log(refreshToken);
          return done(null, {
                    profile,
                    accessToken,
                    refreshToken
                });
        }
      )
    );

第 2 步:在此步骤中使用范围、访问类型和提示对请求进行身份验证

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

© www.soinside.com 2019 - 2024. All rights reserved.