简体   繁体   English

Android Studio - 从 GetIdToken 获取 Firebase 令牌

[英]Android Studio - Get Firebase token from GetIdToken

I have done the following in Swift:我在 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.我现在正在尝试为 Android 做同样的事情。 The firebase documentation touches on the topic but does not explain getting the token extensively. firebase 文档涉及该主题,但没有广泛解释如何获取令牌。 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.错误:解码 Firebase ID 令牌失败。 Make sure you passed the entire string JWT which represents an ID token.确保您传递了代表 ID 令牌的整个字符串 JWT。 See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.有关如何检索 ID 令牌的详细信息,请参阅https://firebase.google.com/docs/auth/admin/verify-id-tokens 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)在 FirebaseAuthError.Error (native) 在 FirebaseAuthError.FirebaseError [作为构造函数] (/user_code/node_modules/firebase-admin/lib/utils/error.js:25:28) 在 new FirebaseAuthError (/user_code/node_modules/firebase-admin/ lib/utils/error.js:90:23) 在 FirebaseTokenGenerator.verifyIdToken (/user_code/node_modules/firebase-admin/lib/auth/token-generator.js:155:35) 在 Auth.verifyIdToken (/user_code/node_modules/ firebase-admin/lib/auth/auth.js:104:37) 在 admin.database.ref.child.child.child.child.child.child.orderByChild.once.then.snapshot (/user_code/index.js: 1430:22) 在 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:我相信这是因为需要有一个 onSuccessListener 但我不确定,也没有成功实现它如下:

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

Your second approach is close, you just need to use <GetTokenResult> instead of <UploadTask.TaskSnapshot> as that is for uploading images using Firebase Storage.您的第二种方法很接近,您只需要使用<GetTokenResult>而不是<UploadTask.TaskSnapshot>因为这是使用 Firebase 存储上传图像。

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);
  }
});

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.");
                                }
                            }
                        }
                    });
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM