To use the authentication information in the security rules of RealtimeDatabase,
I'm trying Firebase custom authentication.
https://firebase.google.com/docs/auth/admin/create-custom-tokens
I created a custom token on the authentication server.
And I authenticated using the created custom token on Android, but an error occurred.
com.google.firebase.auth.FirebaseAuthInvalidCredentialsException:The custom token corresponds to a different audience.
I looked at this thread, but I am wondering what audience is pointing to and what to do specifically.
Firebase token error, "The custom token corresponds to a different audience."
The token payload looks like this:
{
"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"
}
}
The example code on the authentication server:
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);
});
The example code on the 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();
}
}
});
}