Why is Sign in With Google example code returning the wrong token to login to Firebase?

Viewed 40

Working on a Firebase app that will help manage a users Google Calendar.

I am using the official Google Calendar Quickstart Guide code - https://developers.google.com/calendar/api/quickstart/js

Everything works great, I can sign in, authorize access and pull the calendar events.

Firebase allows you to log a user in by passing Firebase a Google ID token.

On this official Firebase guide, https://firebase.google.com/docs/auth/web/google-signin#expandable-2 it shows how to use the Sign In With Google library and then pass the resulting ID token to Firebase to sign in.

Everything works fine on the provided Firebase code until it get to this line.

const idToken = response.credential;

The token returned to the Google Sign In callback doesn't include a credential.

The object has these properties: access_token, expires_in, scope, token_type enter image description here

So when I try to access the .credential on the response it is undefined, so the resulting call to login to Firebase with that credential fails.

The new Sign In With Google flow separates the authentication and authorization. https://developers.google.com/identity/gsi/web/guides/overview#separated_authentication_and_authorization_moments and states

"To enforce this separation, the authentication API can only return ID tokens which are used to sign in to your website, whereas the authorization API can only return code or access tokens which are used only for data access but not sign-in."

Something seems strange because it appears the token being returned is the Google Calendar data access token, when I thought it would be the Google Sign in token.

I've googled every combination, and read any related SO answer I can think of trying to fix this, seems like I am missing something simple.

1 Answers

Figure out it was the wrong token, because when I removed everything out and just tried to implement a basic Sign In With Google, that token works.

Used the Google provided button/popup that their library provides from their guide here:

<div id="g_id_onload"
  data-client_id="CLIENT_ID_GOES_HERE"
  data-callback="handleCredentialResponse">
</div>

In the handleCredentialResponse callback, the returned token did have a .credential

enter image description here

Passing that to Firebase worked to login.

const idToken = response.credential;
const provider = new firebase.auth.GoogleAuthProvider();
const credential = provider.credential(idToken);

auth.signInWithCredential(credential).catch((error) => {
    // Handle Errors here.
});

So obviously I wasn't understanding what was happening in the Google Quick start example.

Now I assume I can use the Google Sign In Token to request Calendar OAuth permissions.

Related