Android Studio – Get Firebase token from GetIdToken

I have done the following in Swift:

let currentUser = Auth.auth().currentUser
currentUser?.getTokenForcingRefresh(true) {idToken, error in
   if let error = error {
     // Handle error
     print("error (below)")
   print("idToken = " + idToken!) // token looks like this: kpJhbGRiOiJSUzI1NiIsIntpZCI9Ijg0MjIuYzc3NTWkOWZmTjI3OBQxZTkyNTpkNWZjZjUwNzg2YTFmNGIifQ.eyJpc3MiOiJodHRwczovL3NlY3Vy... (it's really long)
   // stuff with token

I am now trying to do the equivalent for Android. The firebase documentation touches on the topic but does not explain getting the token extensively. I have tried the following:

Log.d(TAG, user.getIdToken(true));

However, this gives me the following error when I attempt to authenticate this alone on my backend server:

Error: Decoding Firebase ID token failed. Make sure you passed the
entire string JWT which represents an ID token. See for
details on how to retrieve an ID token.
at FirebaseAuthError.Error (native)
at FirebaseAuthError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:25:28)
at new FirebaseAuthError (/user_code/node_modules/firebase-admin/lib/utils/error.js:90:23)
at FirebaseTokenGenerator.verifyIdToken (/user_code/node_modules/firebase-admin/lib/auth/token-generator.js:155:35)
at Auth.verifyIdToken (/user_code/node_modules/firebase-admin/lib/auth/auth.js:104:37)
at admin.database.ref.child.child.child.child.child.child.orderByChild.once.then.snapshot
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

I believe this is because there needs to be an onSuccessListener but am not sure, nor have had success implementing it as follows:

user.getIdToken(true).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
  public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
    Log.d(TAG, "onSuccess: taskSnapshot = " + taskSnapshot);

Your second approach is close, you just need to use OnSuccessListener<GetTokenResult> instead of <UploadTask.TaskSnapshot> as that is for uploading images with Firebase Storage.

Try this:

user.getIdToken(true).addOnSuccessListener(new OnSuccessListener<GetTokenResult>() {
  public void onSuccess(GetTokenResult result) {
    String idToken = result.getToken();
    //Do whatever
    Log.d(TAG, "GetTokenResult result = " + idToken);