我正在尝试让用户授权应用程序进行“离线”访问。
我的令牌网址为“https://oauth2.googleapis.com/token”。我使用一次性
code
、client_id
、client_secret
、scopes
等参数来获取包含令牌的响应。看起来像下面这样:
{
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=json
和 https://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"
}
顺便说一句,您可能需要考虑使用 people api,它比 userinfo 端点稳定得多。
最好在请求标头中发送访问令牌,而不是在 URI 中发送,如 Python 中所述:
def google_auth():
token = google_oauth.google.authorize_access_token()
access_token = token['access_token']
headers = {'Authorization': 'Bearer ' + access_token}
url = 'https://openidconnect.googleapis.com/v1/userinfo'
r = requests.get(url, headers=headers)
r.raise_for_status()
userinfo = r.json()
print(" Google User {}".format(userinfo))
更多信息请访问:Google 发送访问令牌