【问题标题】:How to get Google Fitness API data using OAuth2 with PassportJS如何使用 OAuth2 和 PassportJS 获取 Google Fitness API 数据
【发布时间】:2020-02-08 20:28:31
【问题描述】:

我在使用 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的登录和控制台记录个人资料信息,这是正常的。

有什么想法吗?谢谢。

【问题讨论】:

  • 如果我错了,请有人纠正我,但是您现在不应该能够使用请求的 accessToken 调用健身 api 吗? (https://www.googleapis.com/fitness/v1/users/me/dataSources) 见:https://developers.google.com/fit/rest/v1/get-started

标签: node.js express passport.js google-oauth google-fit


【解决方案1】:

感谢@griFlo 的评论,我明白了。一旦我从身份验证过程中获得了访问令牌,我就必须使用它以及生成的所有其他 api 来调用我想要的 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 承诺部分中,您可以在调用 api 之前检查用户,以便您可以将获取的数据添加到预定义的架构中并保存。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 2019-04-05
    • 2016-04-28
    相关资源
    最近更新 更多