androidgoogle-cloud-platformcredential-managersign-in-with-google

How to Migrate from GoogleSignInClient to Credential Manager for User Authentication in Android?


I'm currently updating my Android app to migrate from GoogleSignInClient to the new Credential Manager for user authentication. Previously, I used GoogleSignInClient to get the user's display name, email address, profile photo, and Google ID(Important). Here's a snippet of the old code that was working fine:

  GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

 private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
            GoogleSignInAccount account = completedTask.getResult();
            if (account != null) {
               photoUrl = account.getPhotoUrl();
               name = account.getDisplayName(); 
               email = account.getEmail();
               googleId = account.getId();// <= crucial for my app's functionality
            } 
     }

Now that GoogleSignInClient is deprecated, I'm trying to use Credential Manager instead. However, I'm having trouble finding a direct replacement for the above functionality.

My Questions:

Any guidance or examples would be greatly appreciated. Thank you!


Solution

  • Answering my own question. Actually, we can get the google user ID from the token itself.

    idToken = googleIdTokenCredential.idToken
    String[] segments = idToken.split("\\.");
    byte[] payloadAsByteArray = Base64.decode(segments[1], Base64.NO_PADDING);
    JSONObject payloadInJson = new JSONObject(new String(payloadAsByteArray, UTF_8));
    String uniqueIdentifier = payloadInJson.get("sub");