Search code examples
google-cloud-firestorefirebase-authenticationfirebase-security

Firestore Rules and custom claim with variable keys


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


Solution

  • 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"
    }