Google Sign In

I recently started using the excellent google_sign_in package to handle Google authentication for access to services on the user’s behalf. Using this a user can allow access to their account in a service like Google Calendar. The documentation is very good but there was one point that tripped me up. In hopes it will save you some time here’s what I discovered.

The login flow goes something like this:

GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: [
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/userinfo.profile",
    // ... other scopes as required by the desired services
  ],
);
GoogleSignInAccount _currentUser;
try {
  _currentUser = await _googleSignIn.signInSilently();
  if (null != _currentUser) {
    return true;
  }
  _currentUser = await _googleSignIn.signIn();
  if (null != _currentUser) {
    return true;
  }
} catch (error) {
  // Do something sensible with the error
}

My initial version didn’t use the signInSilently method and I didn’t at first understand what the use case was. What I missed is that the first time the user signs in successfully using signIn their authentication token is stored and will be reused in future attempts to sign in without the user having to present any credentials. Note that this credential is stored even between application invocations so it supports long lived permission delegation.

To find out if the user has already signed in try signInSilently. That method attempts to retrieve a stored authentication token and use it to re-authenticate. If it works there is a valid authentication and the user doesn’t need to provide their credentials. If not, fallback to signIn which will ask the user to authenticate through a Google presented UI. When I first started working with google_sign_in I’d assumed that I’d be responsible for storing the authentication token between sessions so the user didn’t have to provide their credentials every time. That’s not necessary and makes the package easier to use, and more secure, since not everyone is separately implementing authentication token storage.

Use the signOut or disconnect methods to invalidate the user authentication session and force them to re-authenticate in the future.

Leave a Reply

Your email address will not be published. Required fields are marked *