如何从登录 Google 登录(仅限客户端的应用程序)正确获取访问令牌?

How to properly get Access Token from logged in Google Sign In (client-side only app)?

我正在使用 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);
        },
    });

我打算调用其他 Google API 并且不想使用他们的 Javascript 库(我打算使用 fetch 调用他们的 REST APIs).

但是,当我把Authorization: token.id_token作为Header时,请求被拒绝了。如果我手动输入一个我可以从控制台看到的值 (user.Zi.access_token),它会起作用。

如何从 Google API Javascript SDK 中提取 access_token?使用像 Zi 这样神秘和未记录的东西对我来说似乎不安全。

好的,我在这里找到了relevant documentation。我们可以使用 user.getAuthResponse(true) 来获取带有访问令牌和其他可能有用信息的身份验证响应:

参数为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.

我的问题中的示例工作代码:

let token = user.getAuthResponse(true);
console.log(token.access_token)