Android Studio - Get Firebase token from GetIdToken
Asked Answered
C

2

15

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(error)
     return;
   }
   print("idToken = " + idToken!) // token looks like this: kpJhbGRiOiJSUzI1NiIsIntpZCI9Ijg0MjIuYzc3NTWkOWZmTjI3OBQxZTkyNTpkNWZjZjUwNzg2YTFmNGIifQ.eyJpc3MiOiJodHRwczovL3NlY3Vy... (it's really long)
   //..do 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 https://firebase.google.com/docs/auth/admin/verify-id-tokens 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 (/user_code/index.js:1430:22) 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>() {
  @Override
  public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
    Log.d(TAG, "onSuccess: taskSnapshot = " + taskSnapshot);
  }
});
Carpology answered 1/8, 2017 at 1:48 Comment(0)
C
25

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

Try this:

user.getIdToken(true).addOnSuccessListener(new OnSuccessListener<GetTokenResult>() {
  @Override
  public void onSuccess(GetTokenResult result) {
    String idToken = result.getToken();
    //Do whatever
    Log.d(TAG, "GetTokenResult result = " + idToken);
  }
});
Crystalcrystalline answered 1/8, 2017 at 2:11 Comment(0)
L
1

You can get the user token like below code

        FirebaseAuth mAuth = FirebaseAuth.getInstance();
        mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
information
                                FirebaseUser user = Objects.requireNonNull(task.getResult()).getUser();
                                assert user != null;
                                user.getIdToken(true).addOnSuccessListener(result -> {
                                    String idToken = result.getToken();
                                        //Do whatever
                                    Log.d(TAG, "GetTokenResult result = " + idToken);
                                });
                            } else {
                                if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                                    Toast.makeText(getApplicationContext(), "Your code is not correct!", Toast.LENGTH_SHORT).show();
code.");
                                }
                            }
                        }
                    });
        }
Ladino answered 31/1, 2021 at 10:52 Comment(1)
Please take the time to properly format and indent your code. And just in case you copied the code from someone else, please attribute your source.Siloa

© 2022 - 2024 — McMap. All rights reserved.