Firestore and custom claims - docId not interpreted as a string?

31 views Asked by At

I am using custom claims to grant access to firestore. I have it set already on the user, like so.

admin.auth().setCustomUserClaims(
    userId, {[myId123]:true})

Now I'm trying to write a rule to allow access. Here's what I have written.

match /myCollection/{myDocId} {
  allow read, write: request.auth.token.myDocId;
}

The docId I'm trying to access is myId123, but it is giving me permission denied when I try to access it.

So I manually wrote the rule like so...

match /myCollection/{myDocId} {
  allow read, write: request.auth.token.myId123;
}

... and now I have access. Since this works, I'm thinking that it's not interpreting myDocId to be a variable, but shouldn't myDocId be interpreted as a string there? What am I missing. Why isn't this working.

2

There are 2 answers

0
esafresa On BEST ANSWER

Instead of...

match /myCollection/{myDocId} {
  allow read, write: request.auth.token.myDocId;
}

... you specify the id like ...

match /myCollection/{myDocId} {
  allow read, write: request.auth.token[myDocId];
}
0
Nicolas On

I find a way to make it work, same answer as: Firestore Rules and custom claim with variable keys

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