I have a Firebase Auth custom claim that look like this:
{
"orgRoles": {
"my-org-1": "member",
"my-org-2": "owner",
"my-org-3": "admin"
}
}
Now I want to access it from Firestore Security Rules, kinda like so:
match /organizations/{orgId} {
allow write if: req.auth != null && (req.auth.token.claims.$(orgId) == "admin" || req.auth.token.claims.$(orgId) == "owner")
}
But this doesn't seem to work. Is there actually a way to do this? I am currently storing custom claims in Firestore as well as Firebase Auth.
It's definitely possible to use custom claims in security rules. You're just using the wrong syntax for indexing into the custom claim map using a variable. You're also using the wrong map. The object request.auth.token
contains a Map of custom claims, as described in the documentation.
Firstly, take a look at some similar questions:
The documentation for Map shows how to index it with both a variable (using square brackets []
) and a named property (using .
). This is just like JavaScript. If you have a variable orgId
to index into the map request.auth.token.orgRoles
, then your rule would look like this:
match /organizations/{orgId} {
allow write if: req.auth != null && (req.auth.token.orgRoles[orgId] == "admin" || req.auth.token.orgRoles[orgId] == "owner")
}