通过Google API获取用户信息

gla*_*ola 92 oauth google-api userinfo

是否可以通过Google API从用户的个人资料中获取信息?如果可能,我应该使用哪个API?

我对这些信息感兴趣:

从用户的个人资料中获取其他信息也很酷.

Abh*_*nda 111

将其添加到范围 - https://www.googleapis.com/auth/userinfo.profile

授权完成后,从以下网址获取信息 - https://www.googleapis.com/oauth2/v1/userinfo?alt=json

它有很多东西 - 包括姓名,公共档案网址,性别,照片等.

  • 您提供的网址完美无缺,即https://www.googleapis.com/oauth2/v1/userinfo.但你能告诉你从哪里得到这个网址.我试着寻找它,但没有在任何地方找到它.Google会在某个地方记录这些网址吗? (6认同)
  • 为了供将来参考,请参阅“Google Identity Platform”上的[此](https://developers.google.com/identity/protocols/OpenIDConnect#obtaininguserprofileinformation)页面。该网址与“https://openidconnect.googleapis.com/v1/userinfo”配合使用,响应结构位于“5.从 ID 令牌获取用户信息”部分下。 (3认同)
  • 范围“ userinfo.profile”似乎已被弃用,而应使用“ profile”和“ email”。https://developers.google.com/+/web/api/rest/oauth#authorization-scopes (2认同)
  • 您可以使用用户授权您访问此范围后获得的访问令牌来查询该URL。例如:`curl -X GET“ https://www.googleapis.com/oauth2/v1/userinfo?alt=json” -H“授权:Bearer accessTokenHere” (2认同)

eas*_*son 87

范围 - https://www.googleapis.com/auth/userinfo.profile

return youraccess_token = access_token
Run Code Online (Sandbox Code Playgroud)

获取https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=youraccess_token

你会得到json:

{
 "id": "xx",
 "name": "xx",
 "given_name": "xx",
 "family_name": "xx",
 "link": "xx",
 "picture": "xx",
 "gender": "xx",
 "locale": "xx"
}
Run Code Online (Sandbox Code Playgroud)

致Tahir Yasin:

这是一个php示例.
您可以使用json_decode函数获取userInfo数组.

$q = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxx';
$json = file_get_contents($q);
$userInfoArray = json_decode($json,true);
$googleEmail = $userInfoArray['email'];
$googleFirstName = $userInfoArray['given_name'];
$googleLastName = $userInfoArray['family_name'];
Run Code Online (Sandbox Code Playgroud)

  • 它只给出了id (3认同)

use*_*858 27

此范围https://www.googleapis.com/auth/userinfo.profile现已弃用.请查看https://developers.google.com/+/api/auth-migration#timetable.

您将用于获取个人资料信息的新范围是:个人资料或https://www.googleapis.com/auth/plus.login

端点是 - https://www.googleapis.com/plus/v1/people/ {userId} - userId对于当前登录的用户来说只是'我'.


sin*_*469 24

我正在使用PHP并使用google-api-php-client的 1.1.4版解决了这个问题

假设使用以下代码将用户重定向到Google身份验证页面:

 $client = new Google_Client();
 $client->setAuthConfigFile('/path/to/config/file/here');
 $client->setRedirectUri('https://redirect/url/here');
 $client->setAccessType('offline'); //optional
 $client->setScopes(['profile']); //or email
 $auth_url = $client->createAuthUrl();
 header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
 exit();
Run Code Online (Sandbox Code Playgroud)

假设返回有效的身份验证代码redirect_url,以下内容将从身份验证代码生成令牌并提供基本配置文件信息:

 //assuming a successful authentication code is return
 $authentication_code = 'code-returned-by-google';
 $client = new Google_Client();
 //.... configure $client object code goes here
 $client->authenticate($authentication_code);
 $token_data = $client->getAccessToken();

 //get user email address
 $google_oauth =new Google_Service_Oauth2($client);
 $google_account_email = $google_oauth->userinfo->get()->email;
 //$google_oauth->userinfo->get()->familyName;
 //$google_oauth->userinfo->get()->givenName;
 //$google_oauth->userinfo->get()->name;
 //$google_oauth->userinfo->get()->gender;
 //$google_oauth->userinfo->get()->picture; //profile picture
Run Code Online (Sandbox Code Playgroud)

但是,不会返回位置.新的YouTube帐户没有YouTube特定的用户名


Gle*_*son 8

这是一个糟糕的文件/已经发生了变化。我会参考这个https://developers.google.com/oauthplayground以获得最新的端点。

至于2021正确的端点userinfo

https://www.googleapis.com/oauth2/v1/userinfo

所以一旦你得到access_token你就可以做

curl -X GET "https://www.googleapis.com/oauth2/v1/userinfo" \
   -H "Authorization: Bearer <access_token>"
Run Code Online (Sandbox Code Playgroud)

重要提示:要获取您需要scope的所有信息openid email profile

{
 'sub': '<unique_id>',
 'name': '<full>',
 'given_name': '<first>',
 'family_name': '<last>',
 'picture': '<pic>',
 'email': '<email>',
 'email_verified': True,
 'locale': 'en'
}
Run Code Online (Sandbox Code Playgroud)

  • 超级有用且正确的 2021 答案 - 在我的例子中,“sub”字段是“id”,“email_verified”是“verified_email”,使用带有“v2”承载令牌和“v1”网址 https://www 的 GET。 googleapis.com/oauth2/v2/userinfo 但是 `v3` url 显示了 `sub` 和 `email_verified` 字段,请尝试使用 GET+Bearer for https://www.googleapis.com/oauth2/v3/userinfo (4认同)

Lao*_*aoR 5

我正在使用.Net的Google API,但毫无疑问,您可以找到使用其他版本API获取此信息的相同方法.正如user872858所述,范围userinfo.profile已被弃用(谷歌文章).

要获取用户个人资料信息,我使用以下代码(从谷歌的例子重写部分):

IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
                                  new GoogleAuthorizationCodeFlow.Initializer
                                      {
                                            ClientSecrets = Secrets,
                                            Scopes = new[] { PlusService.Scope.PlusLogin,"https://www.googleapis.com/auth/plus.profile.emails.read"  }
                                       });    
TokenResponse _token = flow.ExchangeCodeForTokenAsync("", code, "postmessage", 
                              CancellationToken.None).Result;

                    // Create an authorization state from the returned token.
                    context.Session["authState"] = _token;

                    // Get tokeninfo for the access token if you want to verify.
                    Oauth2Service service = new Oauth2Service(
                     new Google.Apis.Services.BaseClientService.Initializer());
                    Oauth2Service.TokeninfoRequest request = service.Tokeninfo();
                    request.AccessToken = _token.AccessToken;
                    Tokeninfo info = request.Execute();
                    if (info.VerifiedEmail.HasValue && info.VerifiedEmail.Value)
                    {
                        flow = new GoogleAuthorizationCodeFlow(
                                    new GoogleAuthorizationCodeFlow.Initializer
                                         {
                                             ClientSecrets = Secrets,
                                             Scopes = new[] { PlusService.Scope.PlusLogin }
                                          });

                        UserCredential credential = new UserCredential(flow, 
                                                              "me", _token);
                        _token = credential.Token;
                        _ps = new PlusService(
                              new Google.Apis.Services.BaseClientService.Initializer()
                               {
                                   ApplicationName = "Your app name",
                                   HttpClientInitializer = credential
                               });
                        Person userProfile = _ps.People.Get("me").Execute();
                    }
Run Code Online (Sandbox Code Playgroud)

比,您几乎可以使用userProfile访问任何内容.

更新:要使此代码正常工作,您必须在谷歌登录按钮上使用适当的范围.例如我的按钮:

     <button class="g-signin"
             data-scope="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read"
             data-clientid="646361778467-nb2uipj05c4adlk0vo66k96bv8inqles.apps.googleusercontent.com"
             data-accesstype="offline"
             data-redirecturi="postmessage"
             data-theme="dark"
             data-callback="onSignInCallback"
             data-cookiepolicy="single_host_origin"
             data-width="iconOnly">
     </button>
Run Code Online (Sandbox Code Playgroud)