【问题标题】:Passportjs - How do I request a user's image using the Google strategy?Passportjs - 如何使用 Google 策略请求用户的图像?
【发布时间】:2013-09-29 17:43:26
【问题描述】:

如何配置我的 Google API 访问权限以在进行身份验证时请求用户的图像?目前,“个人资料”仅在用户成功通过身份验证后包含以下属性:

profile.identifier : (字符串)

profile.displayName : (字符串)

profile.emails:(对象)

名称:(对象)

不可以索取用户的账号图片吗?这是我当前的 Passport/Google 策略配置:

passport.use(new GoogleStrategy({
    clientID: CLIENT_ID,
    clientSecret: CLIENT_SECRET, 
    returnURL: 'http://localhost:3000/auth/google/return',
    realm: 'http://localhost:3000'
  },
  function(identifier, profile, done) {
    console.log('identifier ' + identifier)
    for(var p in profile){
        console.log(p + ' : ' + profile[p])
        if(p === 'name'){
            for(var n in profile[p]){
                console.log(n + ' : ' + profile[p][n])
            }
        }
    }
  }
));

您可以看到我正在检查配置文件以查看返回的信息。我认为这需要在我的 Google Api 控制台中以某种方式进行配置。这是 Google+ api 功能吗?

【问题讨论】:

    标签: node.js google-api passport.js


    【解决方案1】:

    passport返回的profile对象,只映射了几个字段:

    profile.id = json.id;
    profile.displayName = json.name;
    profile.name = { familyName: json.family_name,
                     givenName: json.given_name };
    profile.emails = [{ value: json.email }];
    

    但它确实会返回一个包含更多信息的 _json 属性:

    试试:

    var picture = profile._json['picture'];
    

    【讨论】:

    • 这很有趣,因为我看到了人们从 profile._json 属性获取信息的其他示例。但是我的个人资料 obj 中似乎不存在该属性。 profile._json === '未定义'
    • 您正在使用 Google OpenID 策略。请尝试使用 OAuth2。这将返回我在回答中提到的 _json 属性:github.com/jaredhanson/passport-google-oauth
    • 太棒了。 OAuth2 给了我我需要的东西。谢谢!
    【解决方案2】:

    如今,以下两个字段返回用户的图像:

    var picture = '';
    
    picture = profile._json.image.url;
    picture = profile.photos[0].value;
    

    【讨论】:

      【解决方案3】:

      这对我有用。

      profile.photos[0].value
      

      这是它返回的内容

      https://lh3.googleusercontent.com/a-/AOh14GgxnR-ia_f8_hJpUNdD4CoL9IM
      

      【讨论】:

        猜你喜欢
        • 2020-11-22
        • 1970-01-01
        • 1970-01-01
        • 2015-09-07
        • 2017-08-21
        • 2013-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多