如何使用谷歌一键登录提取用户的完整信息?

mik*_*eng 5 javascript oauth-2.0 google-identity google-my-business-api

我正在尝试为谷歌我的业务创建一个平台,并且我已经实现了一键登录,并且我获得了凭据,但没有获得完整的信息。这是我尝试过的代码

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

这是我收到的回复

\n
{\n  clientId:\n    "clientid.apps.googleusercontent.com",\n  credential:\n    "eyJhbGciOiJSUzI1NiIsImtpZCI6ImYwNTQxNWIxM2FjYjk1OT\xe2\x80\xa640Jk8v3LcOvtopFD_tI2HMlFjg0dK96XrqNiOD0H3Akl",\n  select_by: "user",\n};\n
Run Code Online (Sandbox Code Playgroud)\n

Jul*_*ien 18

您可以使用此函数来解析 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);
};
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

    function handleCredentialResponse(response) {
       //console.log(response)
      
        console.log(JSON.stringify(parseJwt(response.credential)));
    }
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述


Gui*_*bin 1

“完整信息”是什么意思?

  1. ID 令牌会在凭据字段中返回。id 令牌包含一些用户的个人资料信息,如https://openid.net/specs/openid-connect-core-1_0.html#IDToken中所定义。要解析 ID 令牌,您可以在https://openid.net/developers/jwt/https://jwt.io/找到一个库。

  2. Google One Tap 不支持 1) 在 ID 令牌中返回更多个人资料信息;2)加载访问令牌以便访问更多用户配置文件数据。您需要查看 Google OAuth 2.0 文档以找到加载访问令牌的方法。

总而言之,Google One Tap 是针对基本 3P 身份验证场景(例如登录和注册等)进行优化的服务。它没有涵盖也不想涵盖所有可能的 OAuth 2.0 场景。