const adminInstance = admin.initializeApp(config)
return adminInstance
.auth()
.createCustomToken(userToLogin.id, {
test: false,
is2faEnabled: false,
})
// token is taken from step 1
firebase.auth().signInWithCustomToken(token)
await adminInstance
.auth()
.setCustomUserClaims(user.id, {
test: true,
newClaimThing: true,
is2faEnabled: true,
})
firebase.auth.currentUser.getIdTokenResult(true).then(console.log)
In console log see the result of claims with:
{
test: false,
newClaimThing: true,
is2faEnabled: false
}
As you can see, only the new claim got set, while the old ones remain.
I've tried calling setCustomUserClaims(user.id, null) first to reset claims, but it didn't work.
Please help! Maybe the flow is incorrect?
createCustomToken is not compatible with setCustomClaims. Its claims will always override the claims you set from the admin SDK after sign in. It is not possible for us to determine if the set claims should override the custom token claims. Therefore the custom token claims will always be the source of truth. To change, you need to mint a new custom token.
Wow, thank you for response, but that's unexpected. "Note: this operation will always overwrite the user's existing custom claims." https://firebase.google.com/docs/auth/admin/custom-claims#set_and_validate_custom_user_claims_via_the_admin_sdk contradicts what you just said. I wish the documentation was properly written.
It is true for non-custom token users. It means that every time you set custom claims on an existing non-custom token user, the claims will be overridden. But I agree that we should provide more clarification in our documentation to explain this special case.
When you use custom tokens, you already have the ability to set the custom claims. You also have the ability to sign in the user in multiple simultaneous sessions with different contradicting claims. Custom token users are a special case. The source of truth has to be the initial claims on the custom token.
Ok, what worked for me is not setting claims on a createCustomToken call but instead setting them only with setCustomUserClaims
I've filed a bug internally to update the documentation on the points discussed here.