2
votes

I have an adminContent node in my Firebase database which should only be read/write accessible if a user has admin set to true as custom claim.

The following code shows that one of my test users HAS admin set to true as claim and one test user HAS NOT (so the problem doesn't seem to be setting the claim correctly):

/* Check if admin */
firebase.auth().currentUser.getIdTokenResult().then(function(idTokenResult) {
   if (idTokenResult.claims.admin) {
    // THIS PART IS EXECUTED

   }
});

These are my rules:

{
  "rules": {
    "metadata": {
      "$user_id": {
        // Read access only granted to the authenticated user.
        ".read": "$user_id === auth.uid",
        // Write access only via Admin SDK.
        ".write": false
      }
    },
    "adminContent": {
      ".read": "auth.token.admin === true",
      ".write": "auth.token.admin === true",
    }
  }
}

Both test users (one with admin claim and one without) are able to read and write to adminContent. And when I test the simulator under rules on the Firebase console with the UIDs of the two users none get permission.

Data structure is as follows:

adminContent
    adminEmails
    announcements
metadata
    ...
users
    ...

Is there anything wrong with my rules? Why do the simulator and real scenario differ?

1

1 Answers

0
votes

It is possible that the token is outdated, ie. the custom claim was set after the ID token was issued. The token lifetime is 1 hour. So until the next refresh, the token will not pick up the latest claims. You can force it to refresh after the custom claim is set by calling:

firebase.auth().currentUser.getIdTokenResult(true)...