要在RealtimeDatabase的安全规则中使用身份验证信息,
我正在尝试Firebase自定义身份验证。
https://firebase.google.com/docs/auth/admin/create-custom-tokens
我在身份验证服务器上创建了一个自定义令牌。
我在Android上使用创建的自定义令牌进行了身份验证,但发生了错误。
com.google.firebase.auth.FirebaseAuthInvalidCredentialsException:自定义令牌对应于其他受众。
我看了这个话题,但是我想知道听众指的是什么以及具体要做些什么。
Firebase token error, "The custom token corresponds to a different audience."
令牌有效载荷如下:
{
"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();
}
}
});
}