如何使用 OAuth2 和 PassportJS 获取 Google 健身 API 数据

How to get Google Fitness API data using OAuth2 with PassportJS

我在使用 Node 和 Express 从 Google Fitness API 获取数据以用于我的应用程序时遇到问题。这是 app.js:

的一部分
app.get('/auth/google', 
    passport.authenticate('google', 
        { scope: ['profile', 'https://www.googleapis.com/auth/fitness.activity.write'] }
));
app.get('<callback url>', 
    passport.authenticate('google'), (req, res) => {
        res.json(req.user);
});

如您所见,我正在请求 2 个不同的范围。这是我使用 passport-google-oauth20 的策略 这是我针对 passport.js:

这个特定数据点的策略
passport.use(
    new GoogleStrategy({
        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret,
        callbackURL:'<callback url>'
    }, (accessToken, refreshToken, profile, done) => {
            console.log(profile);
        } 
    )
)

然而,问题是在控制台中,我只获得第一个范围 "profile" 及其所有属性,但没有健身相关信息。知道它有什么问题吗?我应该使用不同的策略实施吗?目前,此代码在 google 登录时挂起,控制台会记录正常的个人资料信息。

有什么想法吗?谢谢。

正确的范围是:fitness.activity.read

感谢 @griFlo 的评论,我明白了。从身份验证过程中获得访问令牌后,我必须使用此令牌以及已生成的所有其他令牌来调用我想要的 api,我确实使用了来自 request-promise 模块的请求承诺战略。

首先使用 npm i request-promise 安装该模块,并将该模块添加到您的应用程序的顶部。代码应如下所示:

//other defines
...
const request = require('request-promise');

passport.use(
    new GoogleStrategy({
        // options for google strategy
        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret,
        callbackURL:'<callback url>'
    }, (accessToken, refreshToken, profile, done) => {
            User.findOne({googleId: profile.id}).then((currentUser) => {
                if (currentUser){
                    // check user
                    done(null, currentUser);
                } else {
                    //call fitness api
                    url = keys.google.fitnessUrl;
                    request.get(url).auth(null, null, true, accessToken)
                      .then(res=> {
                        new User({
                                googleId: profile.id,
                                ....
                                activity: res
                            }
                        ).save().then((newUser) => {
                           done(null, newUser);
                      });  
                    });
                } 
        });
}));

重要的部分是在 mongoose promise 部分中,您在调用 api 之前检查用户,以便您可以将获取的数据添加到预定义的模式中并保存。