The Firebase Rules docs suggest building conditions comparing the authenticated user's token (i.e., request.auth
) with the target Firestore document(s). Something like:
match /posts/{postId} {
allow read, write: if (request.auth.uid != null) &&
(resource.data.tenantId == request.auth.token.tenantId);
}
However, tenantId
doesn't appear to be available in Firebase Rules like other related auth fields (e.g., uid
, email
, email_verified
, etc.).
One option appears to be to add tenantId
separately as a custom claim using the firebase-admin
SDK. But that would create duplicate info on the user object:
{
uid: 'nzjNp3QIfSR6uWy',
emailVerified: true,
displayName: 'pickleR'
...
tenantId: 'wubalubadubdub',
customClaims: { tenantId: 'wubalubadubdub' },
}
An alternative option appears to be to create a tenants
collection in Firestore. However, that approach seems to introduce needless complexity and inflate the # of required Firestore queries.
Are there alternatives for accessing the tenantId
in Firestore Rules and/or alternative best practices for using Firestore with multi-tenancy?