'Google identity - trigger sign in process on click of custom button
Iam trying to integrate new google identity api in my project. I have a custom button lets say a div
<div class="cust1" onclick="triggerGoogleSignIn">Sign in with Google</div>
now i want sign in to happen, only on click of this button. I checked the documentation and tried g_id_signin class,renderButton method. But these methods are replacing my custom button look.
triggerGoogleSignIn(){
????
}
what method i should call?
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
