Google identity - trigger sign in process on click of custom button

Viewed 2041

I am trying to integrate the 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 should I call?

2 Answers

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

According to documentation:

To support a clear separation of authentication and authorization moments, simultaneously signing a user in to your app and to their Google Account while also issuing an access token is no longer supported.

It looks like with Google Identity Services you can get JWT token within browser only with Sign In With Google

Related