首页 > 解决方案 > Firebase 身份验证使用自定义身份验证系统错误,“自定义令牌对应于不同的受众。”

问题描述

为了在 RealtimeDatabase 的安全规则中使用身份验证信息,
我正在尝试 Firebase 自定义身份验证。
https://firebase.google.com/docs/auth/admin/create-custom-tokens

我在身份验证服务器上创建了一个自定义令牌。
我在 Android 上使用创建的自定义令牌进行了身份验证,但发生了错误。

com.google.firebase.auth.FirebaseAuthInvalidCredentialsException:自定义令牌对应不同的受众。

我看了这个帖子,但我想知道观众指的是什么以及具体做什么。
Firebase 令牌错误,“自定义令牌对应于不同的受众。”

令牌有效负载如下所示:

{
  "aud": "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
  "iat": 1589453768,
  "exp": 1589457368,
  "iss": "firebase-adminsdk-xxxxx@myproject.iam.gserviceaccount.com",
  "sub": "firebase-adminsdk-xxxxx@myproject.iam.gserviceaccount.com",
  "uid": "groupId-userId",
  "claims": {
    "groupId": "groupId"
  }
}

认证服务器上的示例代码:

const admin = require('firebase-admin');
admin.initializeApp();

let uid = groupId + userId; // value from client app
let additionalClaims = {
    groupId: groupId
};
admin.auth().createCustomToken(uid, additionalClaims)
    .then(function(customToken) {
        // Send token back to client
        console.log("CustomToken:" + customToken);
        let response = {
            token: customToken,
            companyCode: companyCode,
            userCode: userCode
        };
        res.type('application/json');
        return res.status(200).send(response);
    })
    .catch(function(error) {
        console.log('Error creating custom token:', error);
    });

Android上的示例代码:

if(!TextUtils.isEmpty(mCustomToken)) {
    mAuth.signInWithCustomToken(mCustomToken)
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    e.printStackTrace();
                }
            })
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success
                        Log.d(TAG, "signInWithCustomToken:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCustomToken:failure", task.getException());
                        Toast.makeText(LoginActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
}

标签: androidfirebasefirebase-authentication

解决方案


推荐阅读