简体   繁体   English

如何从 Google OAuth2 获取用户信息

[英]How to get user info from Google OAuth2

Google is mandating an upgrade to their authentication/authorization mechanism, deprecating their existing mechanism.谷歌正在强制升级他们的身份验证/授权机制,弃用他们现有的机制。

The entire "GoogleAuth" object and all methods is deprecated.不推荐使用整个“GoogleAuth”对象和所有方法。

The migration guidelines provide old->new guidance and examples (many of which don't work as described, but that's another story).迁移指南提供了旧的->新的指导和示例(其中许多不像描述的那样工作,但这是另一回事)。

The old GoogleAuth object had one particularly necessary method .getUserInfo().旧的 GoogleAuth 对象有一个特别必要的方法 .getUserInfo()。

The docs do not provide a migration path for most methods on this object, and not for this one.文档没有为此对象上的大多数方法提供迁移路径,也没有为此对象提供迁移路径。 (The migration doc merely says "remove" with regard to this method.) None of the sample code in migration offer guidance for this. (迁移文档仅针对此方法说“删除”。)迁移中的示例代码都没有为此提供指导。

There is a companion set of docs that describe a different code path, that seems not-entirely-compatible with the new Google Identity Service, and which suggests the user data is embedded in a JWT, but offers no guidance on how to decrypt that JWT.有一组描述不同代码路径的配套文档,似乎与新的 Google 身份服务不完全兼容,并且表明用户数据嵌入在 JWT 中,但没有提供有关如何解密该 JWT 的指导.

My code for authenticating, authorizing, and accessing google's api's is more or less functional (still pops a dialog on every new page load, still working on that), but getting the user info has defeated me after scrutinizing every migration doc, code sample, and considerable searching.我用于验证、授权和访问谷歌 api 的代码或多或少是功能性的(在每次新页面加载时仍会弹出一个对话框,仍在处理中),但在仔细检查了每个迁移文档、代码示例后,获取用户信息让我失望了,和大量的搜索。

Has anyone cracked this nut?有没有人破解过这个坚果?

I am terribly afraid that the answer is so simple that I have spent a full day banging my head on my own stupidity.我非常害怕答案如此简单,以至于我花了一整天的时间来思考自己的愚蠢。

I'm even more afraid it's not possible!我更怕不可能!

Yes, it is possible.对的,这是可能的。 I understand your frustration but your "question" is more about expressing your frustration instead of explaining what you've done so far so we can help you.我理解您的沮丧,但您的“问题”更多的是表达您的沮丧,而不是解释您到目前为止所做的事情,以便我们为您提供帮助。 However, let me try to provide as much help as possible.但是,让我尝试提供尽可能多的帮助。

As you already find out, the "Google Identity Services" is separating "Authorization" and "Authentication" into two different things.正如您已经发现的那样,“Google 身份服务”将“授权”和“身份验证”分为两个不同的东西。 (In my personal opinion, this makes it harder for us developers, although they[google] claim is more secure but I don't see that). (在我个人看来,这让我们开发人员更难了,尽管他们[google] 声称更安全,但我不这么认为)。

I presume that you need the "Authentication" part since you need the user information.我认为您需要“身份验证”部分,因为您需要用户信息。 In that case, you have to follow the guide documented here .在这种情况下,您必须遵循此处记录的指南。

If you will be using the "Sign In With Google" button or the "One Tap" prompt, is up to you.如果您将使用“使用 Google 登录”按钮或“一键式”提示,则取决于您。 I decided to go with the "One Tap" prompt.我决定使用“一键式”提示。 Once you get back the credentials response, you have to decode the JWT that comes in the response.获取凭据响应后,您必须解码响应中的 JWT。 There are many JWT libraries you can use, for the purpose of this example, I am using this one: https://cdnjs.cloudflare.com/ajax/libs/jsrsasign/8.0.20/jsrsasign-all-min.js , however is your responsibility to find a secure library that allows you to do that, hence Google is not recommending any.您可以使用许多 JWT 库,就本示例而言,我使用的是这个: https://cdnjs.cloudflare.com/ajax/libs/jsrsasign/8.0.20/jsrsasign-all-min.js ://cdnjs.cloudflare.com/ajax/libs/jsrsasign/8.0.20/jsrsasign-all-min.js,但是,您有责任找到一个允许您这样做的安全库,因此 Google 不建议这样做。

Here is an example of the code I'm using:这是我正在使用的代码示例:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://accounts.google.com/gsi/client" async defer></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jsrsasign/8.0.20/jsrsasign-all-min.js"></script>
</head>
<body>

  <h1>Hello World!</h1>

  <div id="signinBox"></div>
  
  <script src="app.js"></script>
</body>
</html>

app.js

window.onload = function () {
  google.accounts.id.initialize({
    client_id: 'blablabla.apps.googleusercontent.com',
    callback: handleCredentialResponse,
    ux_mode: "redirect",
    prompt_parent_id: "signinBox",
    context: "signin",
    cancel_on_tap_outside: false,
    auto_select: true
  });
  google.accounts.id.prompt((notification) => {
    if(notification.isNotDisplayed() || notification.isSkippedMoment()) {
      console.log("Prompt cancelled by user");
    }
  });
};

const handleCredentialResponse = (credsResponse)=>{
  console.log(credsResponse);
  var headerObj  = KJUR.jws.JWS.readSafeJSONString(b64utoutf8(credsResponse.credential.split(".")[0]));
  var payloadObj  = KJUR.jws.JWS.readSafeJSONString(b64utoutf8(credsResponse.credential.split(".")[1]));
  console.log(headerObj);
  console.log(payloadObj);
};

After running the above example, you will see the user information in the "payloadObj".运行上述示例后,您将在“payloadObj”中看到用户信息。 It should have all the information as explained here .它应该包含此处解释的所有信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用户登录并在Google OAuth2中同意后,如何获取访问令牌和刷新令牌? - How to get access token and refresh token after user login and consent in Google OAuth2? 从授权码google oauth2获取刷新令牌 - get refresh token from authorization code google oauth2 如何使用Google OAuth2 javascript获取刷新令牌? - How to get a refresh Token with Google OAuth2 javascript? 谷歌 oauth2 获取 id_token - Google oauth2 get id_token Google oauth2使用JavaScript获取accessToken - Google oauth2 get accessToken using javascript 具有多个用户帐户的Google Drive SDK OAuth2 - Google Drive SDK OAuth2 with multiple user account Discord 使用 url-query 中的“代码”发送 Oauth2 重定向 url。 如何在我的谷歌脚本中获取该代码 - Discord send Oauth2 redirect url with the 'code' in url-query. How to get that code in my google script 如何使用 Google OAuth2 REST API 获取“撤销”请求的成功/失败回调? - How to get success/fail callback for `revoke` request with Google OAuth2 REST API? 通过 JavaScript Mastery 在 Shareme 项目上从 Google OAuth 服务恢复用户信息/图像的问题 - Issue to recover user info/image from Google OAuth service on Shareme project by JavaScript Mastery google oauth2获取令牌javascript发布请求 - google oauth2 get token javascript post request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM