首页 > 解决方案 > 如何使用谷歌一键登录提取用户的完整信息?

问题描述

我正在尝试为 Google 我的业务创建一个平台,并且我已经实现了一次点击登录,并且我正在获取凭据但不是完整的信息。这是我尝试过的代码

 <script>
      window.onload = function () {
        google.accounts.id.initialize({
          client_id: "clientid.apps.googleusercontent.com",
          callback: handleCredentialResponse,
        });
        google.accounts.id.prompt((notification) => {
          if (notification.isNotDisplayed() || notification.isSkippedMoment()) {
            console.log("opted out");
          }
        });
        function handleCredentialResponse(response) {
           console.log(response)
          // window.location = "https://github.com/";
        }
      };
    </script>

这是我得到的回应

{
  clientId:
    "clientid.apps.googleusercontent.com",
  credential:
    "eyJhbGciOiJSUzI1NiIsImtpZCI6ImYwNTQxNWIxM2FjYjk1OT…40Jk8v3LcOvtopFD_tI2HMlFjg0dK96XrqNiOD0H3Akl",
  select_by: "user",
};

标签: javascriptoauth-2.0google-identitygoogle-my-business-api

解决方案


您可以使用此函数来解析 JWT 令牌:

function parseJwt (token) {
   var base64Url = token.split('.')[1];
   var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  }).join(''));

  return JSON.parse(jsonPayload);
};

然后你可以这样做:

    function handleCredentialResponse(response) {
       //console.log(response)
      
        console.log(JSON.stringify(parseJwt(response.credential)));
    }

结果:

在此处输入图像描述


推荐阅读