Reputation: 619
I have an issue with my project - Node.js and Firebase.
I want to add an admin role so I use custom claims according to the docs. I have 3 functions in the cloud functions:
exports.addAdminRole = functions.https.onCall((data, context) => {
return admin.auth().setCustomUserClaims(context.auth.uid, {
admin: true
}).then(() =>'Success!')
.catch(err => err)
})
exports.getUserRecord = functions.https.onCall((data, context) => {
return admin.auth().getUser(context.auth.uid)
.then(userRecord => userRecord.customClaims)
.catch(err => err)
})
exports.deleteAdmin = functions.https.onCall((data, context) => {
return admin.auth().setCustomUserClaims(context.auth.uid, null)
.then(() => 'Deleted admin!')
.catch(err => err)
})
I call the functions directly in the client (http callable) and addAdminRole returns 'Success!' and seems to work. getUserRecord seems to work as well and returns {admin: true} as my custom claims.
Now for the problem. I defined a function to get the user claims in the client side like mentioned in the docs:
getRecords() {
firebaseInstance.auth.currentUser.getIdTokenResult()
.then(idTokenResult => {console.log("ADMIN:", idTokenResult)})
.catch(err => console.error(err))
}
(firebaseInstance is imported and works fine in the whole project)
I don't understand why but the code in the client side returns an object with the claims property but this property doesn't have the admin claim I added in the cloud functions.
if I try to access idTokenResult.claims.admin
like in the docs it logs me UNDEFINED.
Link to the docs - https://firebase.google.com/docs/auth/admin/custom-claims#node.js
Could you clarify to me what's wrong? Thank you for your help!
Upvotes: 0
Views: 1204
Reputation: 598797
The claims of a user are stored in their ID token, which is auto-refreshed by the SDK every hour.
Setting a custom claim to a user's profile from the Admin SDK does not force an auto-refresh of the ID token of the clients, so it may take up to an hour before the claim shows up in the clients. The documentation hints at this with:
Once the latest claims have propagated to a user's ID token, you can get them by retrieving the ID token: ...
This documentation could be more explicit though, so I'd recommend leaving feedback with the button at the bottom of that page.
To ensure a claim propagates to a client sooner, you should force the client to refresh its ID token (for example, by passing true
to getIdTokenResult()
.
Upvotes: 7