How to access custom claims inside Cloud Firestore rules?
Asked Answered
T

3

9

I have an user which has the following custom user claims,

 customClaims: { role: 'admin' },

How can I access this role property (admin) inside the cloud firestore rules?

I'm using the code below, which doesn't work. What needs to be done in order to work?

match /companies/{document=**} {
  allow read: if request.auth != null;
  allow write: if request.auth != null && request.customClaims.role == "admin";
}
Tanjatanjore answered 11/10, 2021 at 18:6 Comment(0)
W
14

Custom claims are in request.auth.token object as mentioned in the documentation:

match /companies/{document=**} {
  allow read: if request.auth != null;
  allow write: if request.auth != null && request.auth.token.role == "admin";
}
Wheelwork answered 11/10, 2021 at 18:17 Comment(2)
I have added custom claims but can not access claims in security rules. Also the getIdTokenResult(true) provides my all claims but still can not able to access that claims in rules can anyone help me outReliquary
I had to use request.auth.token.customClaims.roleLura
H
3

All claims (including custom ones) are available under the request.auth.token variable. Note that it may take up to an hour before the claims propagate to the security rules, as they are embedded in the user's ID token. If you want to speed this up, you can force reload the user profile, or sign them out and in again.

Also see:

Hardwick answered 11/10, 2021 at 18:18 Comment(1)
You can re-login into the app as well to test the new rules that uses the custom claims. I was struggling with it because the change to custom claim needs time to be reflected or you just have to sign out and sign back in.Counterscarp
O
1

The custom claims exist in the request.auth.token object as fields , so all the custom claims can be accessed like this request.auth.token[your_custom_claim]

In your case you can access role like this request.auth.token.role

hope that helps :)

Oxendine answered 15/12, 2023 at 19:15 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.