4

I m looking for a way to secure my app using custom claim, but i had difficulty to access them in firestore rules.

My user can be employees of multiple (say 1 to 5) organizations. I would like to had oganizationId(s) as key in the user custom claims and roles as value.

Like that:

claims: {
  "organisationId1":"admin",
  "organisationId2":"regularEmployee",
  "organisationId3":"regularEmployee"
}

Setting the claims via cloud function work well, but i can't find the way to access customs Claims with variable keys

exemple of Security Rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {  
    match /organisations/{oid} {
      allow read: if request.auth.token[oid] == "regularEmployee";
      allow write: if request.auth.token[oid] == "admin";
   }
}

Hope it is possible it would be an easy way to restrict many-to-many relationship

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Nicolas
  • 471
  • 3
  • 6
  • Are you referring to some dictionary you set up on Firebase? Can you please share how the data is being stored in order to know the datatype? – Farid Shumbar Jun 23 '21 at 09:18
  • I'm trying to do this same thing. It's not working for me. Did you find a solution? https://stackoverflow.com/questions/76233140/firestore-and-custom-claims-docid-not-interpreted-as-a-string – esafresa May 12 '23 at 04:41

2 Answers2

1

The Net Ninja actually made a video about this back in 2019 that I just stumbled on.

Basically you want to check for request.auth.token.yourCustomClaim. In my case it looks something like this:

match /orders/{record} {
  allow read, update, delete: request.auth.token.isAdmin == true;
}

Haven't tested it against string values, but I can't think why it wouldn't work. Let us know how it goes, I suppose :)

SeriousLee
  • 1,301
  • 4
  • 20
  • 42
1

I find the way to do it.

 rules_version = '2';
 service cloud.firestore {
   match /databases/{database}/documents {
     match /collection/{documentId} {
       allow read: if true;
       allow write: if request.auth.token.role in ['admin']
     }
 }

It take 'admin' as string and work perfectly fine

And custom claims are like:

claims: {
  role:"admin"
}
Nicolas
  • 471
  • 3
  • 6