In order to get an accesstoken for authorization during your Google API calls, you first authenticate through a OAuth2.0 flow using the following steps:
After loading the library,
<script src="https://accounts.google.com/gsi/client" async defer></script>
you initialize the client by calling :
const tokenClient = google.accounts.oauth2.initTokenClient({
client_id: "YOUR_GOOGLE_CLIENT_ID",
scope: "THE_REQUESTED_SCOPES",
prompt: "SELECT_A_PROMPT_OPTION", // '' | 'none' | 'consent' | 'select_account'
callback: handleCredentialResponse // your function to handle the response after login. 'access_token' will be returned as property on the response
});
In order to request a new access token, call requestAccessToken.
const overrideConfig = {
prompt: "SELECT_A_PROMPT_OPTION", // '' | 'none' | 'consent' | 'select_account'
}
tokenClient.requestAccessToken(overrideConfig) // open the prompt, overrideConfig is optional
Types can be found here and installed by executing npm install --save-dev @types/google.accounts
If you need an id_token for authentication to sign in into your own application, you can opt for the Sign In With Google button.
If you want to render your own button and trigger the authentication flow through javascript, use the following steps:
Include the client library in your head tag
<script src="https://accounts.google.com/gsi/client" async defer></script>
After loading the library, you initialize with your client_id, and set a callback to handle the response after sign in.
function handleCredentialResponse(response) {
var id_token = response.credential // validate and decode the JWT credential, using a JWT-decoding library
}
window.onload = function () {
google.accounts.id.initialize({
client_id: "YOUR_GOOGLE_CLIENT_ID",
callback: handleCredentialResponse
});
}
To sign in, just call the prompt.
google.accounts.id.prompt();
Types can be found here and installed by executing npm install --save-dev @types/google-one-tap