I am using Google Sign-In button to let user logging in with their Google Account:
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).
However, when I put Authorization: token.id_token
as Header, the request is rejected. If I manually put a value that I can see from the Console (user.Zi.access_token
), it works.
How can I extract the access_token
from Google API Javascript SDK? Using something cryptic and undocumented like Zi
does not seem safe to me.
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:
The parameter is 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.
Example working code from my question:
let token = user.getAuthResponse(true);
console.log(token.access_token)