首页 > 解决方案 > 定义正确的 Firestore 安全规则

问题描述

我是 Firebase Firestore 的新手,我想定义安全规则。如图所示,我的数据结构非常简单。

数据结构

每个用户都有自己的带有子集合的文档。我希望用户只能读写他自己的文档(包括子集合中的文档),所以我的规则应该是这样的:

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, update, delete: if request.auth != null && request.auth.uid == userId;
      allow create: if request.auth != null;
    }
  }
}

使用此代码,用户是否也可以读取和写入子集合中的文档?还有什么重要的我需要添加到安全规则中或者这就是我需要做的吗?

标签: google-cloud-firestorefirebase-authenticationfirebase-security

解决方案


规则中的match语句控制这些规则适用的内容。在你的情况下:

match /users/{userId} {

此规则适用于users集合本身中的文档,而不适用于子集合中的文档。


如果您也想对所有子集合应用相同的规则,您可以使用递归通配符匹配( =**),如下所示:

match /users/{userId=**} {

不是这样,相同的规则适用于users集合中的文档,以及那里的所有子集合/文档。


您还可以通过为子集合嵌套match子句来更精细地控制对子集合的访问。例如,假设您有一个子集合messages,并且您只想允许用户读取该子集合的访问权限,您可以使用以下规则来实现:

match /users/{userId} {
  allow read, update, delete: if request.auth != null && request.auth.uid == userId;
  allow create: if request.auth != null;
  match /messages/{messageId} {
    allow read: if request.auth != null && request.auth.uid == userId;
  }
}

如您所见,我们在这里逐字重复条件,因此在自定义命名函数中捕获条件以提高可读性和可维护性是很常见的。


推荐阅读