【问题标题】:Get user info via Google API通过 Google API 获取用户信息
【发布时间】:2011-10-31 03:11:53
【问题描述】:

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

我对这些信息很感兴趣:

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

【问题讨论】:

    标签: oauth google-api userinfo


    【解决方案1】:

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

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

    它有很多东西——包括姓名、公开资料网址、性别、照片等。

    【讨论】:

    • 我使用了上面的网址,但无法获取用户的个人资料。仅获取“{”。请你可以发布一些代码或链接。提前致谢。
    • 您提供的网址完美运行,即 googleapis.com/oauth2/v1/userinfo 。但是你能告诉你这个网址是从哪里得到的吗?我试图搜索它,但在任何地方都没有找到它。 Google 会在某个地方记录这些网址吗?
    • 在哪里可以查看特定范围返回的数据规范?
    • Scope "userinfo.profile" 似乎已被弃用,您应该使用“profile”和“email”。 developers.google.com/+/web/api/rest/oauth#authorization-scopes
    • 您可以使用在用户授权您访问此范围后获得的访问令牌来查询此 url。示例:curl -X GET "https://www.googleapis.com/oauth2/v1/userinfo?alt=json" -H"Authorization: Bearer accessTokenHere"
    【解决方案2】:

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

    return youraccess_token = access_token
    

    获取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"
    }
    

    致塔希尔·亚辛:

    这是一个 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'];
    

    【讨论】:

    • 我如何使用他们的回复?
    • 我怎样才能得到电子邮件地址以及您提到的其他信息?
    • 请更新代码以具有正确的格式以访问$userInfoArray 属性。从$userInfoArray 获取电子邮件地址应该类似于$userInfoArray['email']。注意访问属性的单引号。
    • @Shantha Kumara 你可以自己编辑它,但不用担心,因为我现在已经完成了。据我们所知,他们本可以省略代码define(email, 'email') ;)
    • 我想获取电话号码和年龄/生日
    【解决方案3】:

    这个范围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 可以只是“我”。

    【讨论】:

    • 这是一个重要的信息和平对具有集成未来证明。有关已弃用范围的更多信息developers.google.com/+/web/api/rest/oauth
    • 还有……If you are directly requesting the “plus.me” scope, any other Google+ OAuth scopes, or making any Google+ API calls, please ensure that you remove these requests from your project before March 7, 2019. -- Google
    【解决方案4】:

    我正在使用 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();
    

    假设向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
    

    但是,不返回位置。 New YouTube accounts don't have YouTube specific usernames

    【讨论】:

    • 如何获取位置?
    • 我无法使用此范围获取性别信息(我已公开性别信息)。我为此尝试过 oauth playground developers.google.com/oauthplayground。我想在服务器端使用 REST API 来做到这一点。你能帮我解决这个问题吗?
    • 也无法获取性别。并且在某些情况下,除了电子邮件之外什么都没有返回。想法?
    【解决方案5】:

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

    截至2021userinfo 的正确端点是

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

    因此,一旦您获得access_token,您就可以这样做

    curl -X GET "https://www.googleapis.com/oauth2/v1/userinfo" \
       -H "Authorization: Bearer <access_token>"
    

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

    {
     'sub': '<unique_id>',
     'name': '<full>',
     'given_name': '<first>',
     'family_name': '<last>',
     'picture': '<pic>',
     'email': '<email>',
     'email_verified': True,
     'locale': 'en'
    }
    

    【讨论】:

    • 我一直在努力寻找专门的电子邮件字段,这个答案解决了我的问题!我可以验证这是否有效。谢谢!
    • 超级有用和正确的 2021 年答案——在我的情况下,“子”字段是 id,而“email_verified”是 verified_email,使用带有承载令牌 v2 和 @987654335 的 GET @ urls googleapis.com/oauth2/v2/userinfo 但是 v3 url 显示 subemail_verified 字段,请尝试使用 GET+Bearer 获取 googleapis.com/oauth2/v3/userinfo
    • 啊有趣的是没有太关注版本,但听起来他们之间的反应有些不同。
    【解决方案6】:

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

    为了获取用户个人资料信息,我使用以下代码(从google's example 重写的部分):

    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();
                        }
    

    然后,您几乎可以使用 userProfile 访问任何内容。

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

         <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>
    

    【讨论】:

      【解决方案7】:

      需要运行 3 个步骤。

      1. 从 Google API 控制台注册您应用的客户端 ID
      2. 请您的最终用户同意使用此 API https://developers.google.com/identity/protocols/OpenIDConnect#sendauthrequest
      3. 使用在步骤 2 中获得的令牌,使用 google 的 oauth2 api,如 https://any-api.com/googleapis_com/oauth2/docs/userinfo/oauth2_userinfo_v2_me_get 所述。(虽然我仍然找不到如何正确填写“字段”参数)。

      有趣的是,这种最简单的用法在任何地方都没有清楚地描述。 我相信存在危险,您应该注意响应中的verified_email参数。因为如果我没记错,它可能会产生虚假电子邮件来注册您的应用程序。 (这只是我的解释,很有可能我错了!)

      我发现 facebook 的 OAuth 机制描述得非常清楚。

      【讨论】:

        【解决方案8】:

        如果您只想为 Web 应用程序的访问者获取 Google 用户 ID、姓名和图片 - 这是我在 2020 年使用的纯 PHP 服务端解决方案,不使用外部库 -

        如果您阅读了 Google 的 Using OAuth 2.0 for Web Server Applications 指南(请注意,Google 喜欢更改指向其自己文档的链接),那么您只需执行 2 个步骤:

        1. 向访问者展示一个网页,请求其同意与您的网络应用分享她的名字
        2. 然后将上述网页传递的“代码”带到您的网络应用,并从 Google 获取一个令牌(实际上是 2 个)。

        其中一个返回的令牌称为“id_token”,包含访问者的用户 ID、姓名和照片。

        这是我写的a web game的PHP代码。最初我使用的是 Javascript SDK,但后来我注意到,当仅使用客户端 SDK(尤其是用户 ID,这对我的游戏很重要)时,虚假的用户数据可能会传递到我的网页游戏,所以我已经切换到使用服务器端的PHP:

        <?php
        
        const APP_ID       = '1234567890-abcdefghijklmnop.apps.googleusercontent.com';
        const APP_SECRET   = 'abcdefghijklmnopq';
        
        const REDIRECT_URI = 'https://the/url/of/this/PHP/script/';
        const LOCATION     = 'Location: https://accounts.google.com/o/oauth2/v2/auth?';
        const TOKEN_URL    = 'https://oauth2.googleapis.com/token';
        const ERROR        = 'error';
        const CODE         = 'code';
        const STATE        = 'state';
        const ID_TOKEN     = 'id_token';
        
        # use a "random" string based on the current date as protection against CSRF
        $CSRF_PROTECTION   = md5(date('m.d.y'));
        
        if (isset($_REQUEST[ERROR]) && $_REQUEST[ERROR]) {
            exit($_REQUEST[ERROR]);
        }
        
        if (isset($_REQUEST[CODE]) && $_REQUEST[CODE] && $CSRF_PROTECTION == $_REQUEST[STATE]) {
            $tokenRequest = [
                'code'          => $_REQUEST[CODE],
                'client_id'     => APP_ID,
                'client_secret' => APP_SECRET,
                'redirect_uri'  => REDIRECT_URI,
                'grant_type'    => 'authorization_code',
            ];
        
            $postContext = stream_context_create([
                'http' => [
                    'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method'  => 'POST',
                    'content' => http_build_query($tokenRequest)
                ]
            ]);
        
            # Step #2: send POST request to token URL and decode the returned JWT id_token
            $tokenResult = json_decode(file_get_contents(TOKEN_URL, false, $postContext), true);
            error_log(print_r($tokenResult, true));
            $id_token    = $tokenResult[ID_TOKEN];
            # Beware - the following code does not verify the JWT signature! 
            $userResult  = json_decode(base64_decode(str_replace('_', '/', str_replace('-', '+', explode('.', $id_token)[1]))), true);
        
            $user_id     = $userResult['sub'];
            $given_name  = $userResult['given_name'];
            $family_name = $userResult['family_name'];
            $photo       = $userResult['picture'];
        
            if ($user_id != NULL && $given_name != NULL) {
                # print your web app or game here, based on $user_id etc.
                exit();
            }
        }
        
        $userConsent = [
            'client_id'     => APP_ID,
            'redirect_uri'  => REDIRECT_URI,
            'response_type' => 'code',
            'scope'         => 'profile',
            'state'         => $CSRF_PROTECTION,
        ];
        
        # Step #1: redirect user to a the Google page asking for user consent
        header(LOCATION . http_build_query($userConsent));
        
        ?>
        

        您可以使用 PHP 库通过验证 JWT 签名来增加额外的安全性。出于我的目的,这是不必要的,因为我相信 Google 不会通过发送虚假的访问者数据来背叛我的小网页游戏。

        另外,如果你想获取更多访问者的个人数据,那么你需要第三步:

        const USER_INFO    = 'https://www.googleapis.com/oauth2/v3/userinfo?access_token=';
        const ACCESS_TOKEN = 'access_token'; 
        
        # Step #3: send GET request to user info URL
        $access_token = $tokenResult[ACCESS_TOKEN];
        $userResult = json_decode(file_get_contents(USER_INFO . $access_token), true);
        

        或者您可以代表用户获得更多权限 - 请参阅OAuth 2.0 Scopes for Google APIs 文档中的长列表。

        最后,我的代码中使用的 APP_ID 和 APP_SECRET 常量 - 你可以从 Google API console 获得它:

        【讨论】:

          【解决方案9】:

          如果您在客户端 Web 环境中,新的 auth2 javascript API 包含一个非常需要的 getBasicProfile() 函数,该函数返回用户的姓名、电子邮件和图像 URL。

          https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile

          【讨论】:

          • 但是实际的 API URL 是什么?我查看了文档,找不到实际的 API URL。 Google 似乎在推动我们使用他们的 SDK,但并不是每个人都想使用 SDK。
          猜你喜欢
          • 2016-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-19
          • 2015-11-22
          • 1970-01-01
          • 2012-11-28
          • 1970-01-01
          相关资源
          最近更新 更多