从 Google 用户信息端点获取 401

问题描述

我正在尝试让用户授权该应用进行“离线”访问。

我的令牌网址为“https://oauth2.googleapis.com/token”。我使用一次性 codeclient_idclient_secretscopes 等参数来获取包含令牌的响应。如下图所示:

{
  access_token: ...,expires_in: 3599,refresh_token: ...,scope: ...,token_type: 'Bearer'
}

我从上面的响应中获取 access_token 值并尝试使用它从“https://www.googleapis.com/oauth2/v1/userinfo?alt=json”中提取 userInfo 并且它总是返回 401。

我用代码和 curl 做到了,试图将授权标头中的令牌传递为

const headers = {
  Authorization: `Bearer ${accesstoken}`
};
const userInfo = await fetch('https://www.googleapis.com/oauth2/v1/userinfo?alt=json',{headers});

并且还尝试将 access_token 添加查询字符串,以及针对较新的端点(例如 https://www.googleapis.com/oauth2/v2/userinfo?alt=jsonhttps://www.googleapis.com/oauth2/v4/userinfo?alt=json)执行。

我总是收到 401。消息是:Request is missing required authentication credentials...

我应该怎么做?

解决方法

userinfo 端点是一个 HTTP GET 调用,您可以将访问令牌字符串作为查询参数。

https://openidconnect.googleapis.com/v1/userinfo?access_token=ya29.a0AfH6SMDfRQFdEOxq97LXqUa1jwdtRLSD2l_hiLFeaWYXRBB6gIkh7XHko75xj70uPnuOppKtf0c 

回复

{
  "sub": "1172004755326746","name": "Linda Lawton","given_name": "Linda","family_name": "Lawton","picture": "https://lh3.googleusercontent.com/a-/AOh14GhroCYJp2P9xeYeYk1npchBPK-zbtTxzNQo0WAHI20\u003ds96-c","locale": "en"
}

顺便说一句,您可能需要考虑使用 https://dbfiddle.uk/?rdbms=mariadb_10.3&fiddle=0f681dc8d93cc3eebf9a03e0c8d84850 代替它比 userinfo 端点稳定得多。