具有多租户的 Firestore 规则?

Firestore Rules with multi-tenancy?

Firebase Rules docs 建议构建条件,将经过身份验证的用户的令牌(即 request.auth)与目标 Firestore 文档进行比较。类似于:

match /posts/{postId} {
  allow read, write: if (request.auth.uid != null) && 
    (resource.data.tenantId == request.auth.token.tenantId);
}

但是,tenantId 似乎在 Firebase Rules 中不可用,就像其他相关的身份验证字段(例如,uidemailemail_verified等)。

一个选项似乎是使用 firebase-admin SDK 将 tenantId 作为 custom claim 单独添加。但这会在用户对象上创建重复信息:

{
  uid: 'nzjNp3QIfSR6uWy',
  emailVerified: true,
  displayName: 'pickleR'
  ...
  tenantId: 'wubalubadubdub',
  customClaims: { tenantId: 'wubalubadubdub' },
}

alternative option 似乎要在 Firestore 中创建一个 tenants 集合。但是,这种方法似乎引入了不必要的复杂性并增加了所需 Firestore 查询的数量。

是否有其他方法可以访问 Firestore 规则中的 tenantId and/or 将 Firestore 用于多租户的替代最佳实践?

您描述的两个选项是惯用的选项:

  1. 将信息作为 ID 令牌的一部分作为自定义声明传递到规则中。
  2. 通过request.auth.uid.
  3. 规则从数据库中查找信息

这两种方法都不总是比另一种更好:自定义声明更方便、更易读,而使用数据库通常更快。通常使用数据库查找更多易变信息,并声明“一次”的信息。

由于这是针对租户 ID 的,不太可能快速更改,因此我可能会选择自定义声明。

沿着自定义声明路线走下去后,我发现租户 ID 已经存储在嵌套对象中,如 'request.auth.token.firebase.tenant'

在您的示例中,规则为:

match /posts/{postId} {
  allow read, write: if (request.auth.uid != null) && 
    (resource.data.tenantId == request.auth.token.firebase.tenant);
}