[英]How to properly get Access Token from logged in Google Sign In (client-side only app)?
I am using Google Sign-In button to let user logging in with their Google Account: 我正在使用Google登录按钮让用户使用其Google帐户登录:
gapi.signin2.render("container-btn-google-login", {
scope: "email profile",
onsuccess: (user) => {
let token = user.getAuthResponse();
setToken(token);
// How can I get the Access Token here
// that should be the same as user.Zi.access_token?
resolve(token);
},
});
I am going to call other Google APIs and do not want to use their Javascript library (I am going to use fetch
to call their REST APIs). 我打算调用其他Google API,不想使用他们的Javascript库(我将使用
fetch
来调用他们的REST API)。
However, when I put Authorization: token.id_token
as Header, the request is rejected. 但是,当我将
Authorization: token.id_token
作为Header时,请求被拒绝。 If I manually put a value that I can see from the Console ( user.Zi.access_token
), it works. 如果我手动设置我可以从控制台(
user.Zi.access_token
)看到的值,它就可以工作。
How can I extract the access_token
from Google API Javascript SDK? 如何从Google API Javascript SDK中提取
access_token
? Using something cryptic and undocumented like Zi
does not seem safe to me. 使用像
Zi
这样神秘而无证的东西对我来说似乎并不安全。
Okay, I have found the relevant documentation here. 好的,我在这里找到了相关文档 。 We can use
user.getAuthResponse(true)
to get the Auth Response with the access token and possibly other useful information: 我们可以使用
user.getAuthResponse(true)
来获取带有访问令牌的Auth响应以及可能的其他有用信息:
The parameter is includeAuthorizationData
: 参数是
includeAuthorizationData
:
Optional: A boolean that specifies whether to always return an access token and scopes.
可选:一个布尔值,指定是否始终返回访问令牌和范围。 By default, the access token and requested scopes are not returned when fetch_basic_profile is true (the default value) and no additional scopes are requested.
默认情况下,当fetch_basic_profile为true(默认值)且未请求其他范围时,不会返回访问令牌和请求的范围。
Example working code from my question: 我的问题中的工作代码示例:
let token = user.getAuthResponse(true);
console.log(token.access_token)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.