通过Google API获取用户信息

发布于 2024-12-01 01:55:44 字数 315 浏览 1 评论 0 原文

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

我对此类信息感兴趣:

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

Is it possible to get information from user's profile via Google API? If it is possible, which API should I use?

I'm interesting in such information:

Also it would be cool to get other information from user's profile.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

糖粟与秋泊 2024-12-08 01:55:44

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

并在授权后完成后,从 - https://www.googleapis.com/oauth2/v1/userinfo? alt=json

它包含大量内容 - 包括姓名、公共个人资料网址、性别、照片等。

Add this to the scope - https://www.googleapis.com/auth/userinfo.profile

And after authorization is done, get the information from - https://www.googleapis.com/oauth2/v1/userinfo?alt=json

It has loads of stuff - including name, public profile url, gender, photo etc.

失眠症患者 2024-12-08 01:55:44

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

return youraccess_token = access_token

获取 < a href="https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=youraccess_token" rel="noreferrer">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"
}

致 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'];

scope - https://www.googleapis.com/auth/userinfo.profile

return youraccess_token = access_token

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

you will get json:

{
 "id": "xx",
 "name": "xx",
 "given_name": "xx",
 "family_name": "xx",
 "link": "xx",
 "picture": "xx",
 "gender": "xx",
 "locale": "xx"
}

To Tahir Yasin:

This is a php example.
You can use json_decode function to get userInfo array.

$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'];
ゝ杯具 2024-12-08 01:55:44

这是一个糟糕的文档/已经发生了变化。我会参考此 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>"

重要:获取 openid 电子邮件配置文件范围所需的所有信息。

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

This is poorly document / there have been changes. I would reference this https://developers.google.com/oauthplayground for up to date endpoints.

As of 2021 the correct endpoint for userinfo is

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

So once you get the access_token you can do

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

Important: To get all the information you need 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'
}
何以笙箫默 2024-12-08 01:55:44

This scope https://www.googleapis.com/auth/userinfo.profile has been deprecated now. Please look at https://developers.google.com/+/api/auth-migration#timetable.

New scope you will be using to get profile info is: profile or https://www.googleapis.com/auth/plus.login

and the endpoint is - https://www.googleapis.com/plus/v1/people/{userId} - userId can be just 'me' for currently logged in user.

隐诗 2024-12-08 01:55:44

我正在使用 PHP 并通过使用 google-api-php-client

假设以下代码用于将用户重定向到 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

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

I'm using PHP and solved this by using version 1.1.4 of google-api-php-client

Assuming the following code is used to redirect a user to the Google authentication page:

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

Assuming a valid authentication code is returned to the redirect_url, the following will generate a token from the authentication code as well as provide basic profile information:

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

However, location is not returned. New YouTube accounts don't have YouTube specific usernames

我是男神闪亮亮 2024-12-08 01:55:44

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

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

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 访问几乎任何内容。

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

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

I am using Google API for .Net, but no doubt you can find the same way to obtain this information using other version of API.
As user872858 mentioned, scope userinfo.profile has been deprecated (google article) .

To obtain user profile info I use following code (re-written part from 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();
                    }

Than, you can access almost anything using userProfile.

UPDATE: To get this code working you have to use appropriate scopes on google sign in button. For example my button:

     <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>
清君侧 2024-12-08 01:55:44

如果您使用Oath2,那么客户端将提供id_token

,然后您可以使用此网址在服务器上验证它

https://oauth2.googleapis.com/tokeninfo?id_token=your_id_token

将解决诸如幸运符之类的问题

if you use Oath2 then client will give id_token

then you can validate it on server with this url

https://oauth2.googleapis.com/tokeninfo?id_token=your_id_token

will solve problem like lucky charm

您的好友蓝忘机已上羡 2024-12-08 01:55:44

需要运行 3 个步骤。

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

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

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

There are 3 steps that needs to be run.

  1. Register your app's client id from Google API console
  2. Ask your end user to give consent using this api https://developers.google.com/identity/protocols/OpenIDConnect#sendauthrequest
  3. Use google's oauth2 api as described at https://any-api.com/googleapis_com/oauth2/docs/userinfo/oauth2_userinfo_v2_me_get using the token obtained in step 2. (Though still I could not find how to fill "fields" parameter properly).

It is very interesting that this simplest usage is not clearly described anywhere. And i believe there is a danger, you should pay attention to the verified_emailparameter coming in the response. Because if I am not wrong it may yield fake emails to register your application. (This is just my interpretation, has a fair chance that I may be wrong!)

I find facebook's OAuth mechanics much much clearly described.

街道布景 2024-12-08 01:55:44

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

如果您阅读 将 OAuth 2.0 用于 Web 服务器应用程序 Google 指南(请注意,Google喜欢更改指向其自己文档的链接),那么您只需执行 2 个步骤:

  1. 向访问者呈现一个网页,请求其同意与您的 Web 应用程序共享她的姓名
  2. 然后将上述网页传递的“代码”传递给您的网络应用程序并从 Google 获取令牌(实际上是 2)。

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

这是我编写的网页游戏的 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 签名来添加额外的安全性。就我的目的而言,这是不必要的,因为我相信谷歌不会通过发送虚假的访问者数据来背叛我的小网页游戏。

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

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

或者您可以代表用户获取更多权限 - 请参阅 Google API 的 OAuth 2.0 范围 文档。

最后,我的代码中使用的 APP_ID 和 APP_SECRET 常量 - 您可以从 Google API 控制台获取它:

If you only want to fetch the Google user id, name and picture for a visitor of your web app - here is my pure PHP service side solution for the year 2020 with no external libraries used -

If you read the Using OAuth 2.0 for Web Server Applications guide by Google (and beware, Google likes to change links to its own documentation), then you have to perform only 2 steps:

  1. Present the visitor a web page asking for the consent to share her name with your web app
  2. Then take the "code" passed by the above web page to your web app and fetch a token (actually 2) from Google.

One of the returned tokens is called "id_token" and contains the user id, name and photo of the visitor.

Here is the PHP code of a web game by me. Initially I was using Javascript SDK, but then I have noticed that fake user data could be passed to my web game, when using client side SDK only (especially the user id, which is important for my game), so I have switched to using PHP on the server side:

<?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));

?>

You could use a PHP library to add additional security by verifying the JWT signature. For my purposes it was unnecessary, because I trust that Google will not betray my little web game by sending fake visitor data.

Also, if you want to get more personal data of the visitor, then you need a third step:

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

Or you could get more permissions on behalf of the user - see the long list at the OAuth 2.0 Scopes for Google APIs doc.

Finally, the APP_ID and APP_SECRET constants used in my code - you get it from the Google API console:

screenshot

小女人ら 2024-12-08 01:55:44

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

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

If you're in a client-side web environment, the new auth2 javascript API contains a much-needed getBasicProfile() function, which returns the user's name, email, and image URL.

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

感情废物 2024-12-08 01:55:44

获取 idaccessToken 的方法

这就是我使用新的 Google Identity Services API JS 代码

<script src="https://accounts.google.com/gsi/client" async></script>
$(document).on("click", ".login-google", function(e) {
    const client = google.accounts.oauth2.initTokenClient({
        client_id: 'your_client_id',
        scope: 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',
        callback: (tokenResponse) => {
            if (tokenResponse && tokenResponse.access_token) {
                $.ajax({
                    type: "GET",
                    url: "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + tokenResponse.access_token,
                    contentType: "application/json",
                    success: function(data) {
                        let externalModel = {
                            authProvider: 'Google',
                            providerKey: data.id,
                            providerAccessCode: tokenResponse.access_token
                        };
                        abp.ui.setBusy();
                        abp.ajax({
                            url: window.location.origin + '/api/SocialLogin',
                            type: 'POST',
                            dataType: 'json',
                            contentType: 'application/json',
                            data: JSON.stringify(externalModel),
                            success: function(data) {
                                if (data.accessToken) {
                                    location.href = window.location.origin;
                                }
                                abp.ui.clearBusy();
                            },
                            error: function(e) {
                                console.log("error on login:", e)
                            }
                        }).always(function() {
                            abp.ui.clearBusy();
                        });
                    }
                });
            }
        },
    });
    client.requestAccessToken();
});

解释

  1. 添加 gsi/client 脚本
  2. 在按钮上单击 创建 TokenClient 对象
  3. 传递三个参数(client_id、scope 和将获取令牌响应的回调)
  4. 调用 client.requestAccessToken(); 方法 弹出Google登录界面
  5. 成功后 google 登录,响应将由您在 TokenClient 参数中提到的回调处理程序处理
  6. 创建一个到 获取个人资料 URL 并在查询字符串参数中传递 accessToken。
  7. 在其成功方法中,您将看到配置文件信息
  8. 其余任务由我的后端管理,即使用 .Net Core 2.2 的 ASPNet Boilerplate

This is how I get the id and accessToken using the new Google Identity Services API

JS Code

<script src="https://accounts.google.com/gsi/client" async></script>
$(document).on("click", ".login-google", function(e) {
    const client = google.accounts.oauth2.initTokenClient({
        client_id: 'your_client_id',
        scope: 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',
        callback: (tokenResponse) => {
            if (tokenResponse && tokenResponse.access_token) {
                $.ajax({
                    type: "GET",
                    url: "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + tokenResponse.access_token,
                    contentType: "application/json",
                    success: function(data) {
                        let externalModel = {
                            authProvider: 'Google',
                            providerKey: data.id,
                            providerAccessCode: tokenResponse.access_token
                        };
                        abp.ui.setBusy();
                        abp.ajax({
                            url: window.location.origin + '/api/SocialLogin',
                            type: 'POST',
                            dataType: 'json',
                            contentType: 'application/json',
                            data: JSON.stringify(externalModel),
                            success: function(data) {
                                if (data.accessToken) {
                                    location.href = window.location.origin;
                                }
                                abp.ui.clearBusy();
                            },
                            error: function(e) {
                                console.log("error on login:", e)
                            }
                        }).always(function() {
                            abp.ui.clearBusy();
                        });
                    }
                });
            }
        },
    });
    client.requestAccessToken();
});

Explanation

  1. Add gsi/client script
  2. On the button click Create an object of TokenClient
  3. Pass three parameters (client_id, scope, and callback which will get the token response)
  4. Call client.requestAccessToken(); method to popup Google sign-in screen
  5. After a successful google signin, response will be handled by the callback handler that you mention in the TokenClient parameters
  6. Create a get request to Get Profile URL and pass accessToken in the query string parameter.
  7. On its success method you will see the profile informations
  8. The rest of the tasks are managed by my backend which is ASPNet Boilerplate using .Net Core 2.2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文