针对特定集合的 Firebase 安全规则?

Firebase Security Rules to specific Collection?

我有三个合集,Collect 1Collection 2,只有经过身份验证的用户才能阅读。第三个集合是 Users,只有经过身份验证的用户才能读取、写入、更新和删除,但只能是具有各自 UID 的文档。当前规则适用于所有集合。当前的安全规则是:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read: if request.auth != null;
    }
  }
}

Only authenticated users can read, write, update and delete but only the document with their respective UID

您没有说明用户的 UID 如何与 Firestore 文档 ID 相关联。基本上有两种情况:

1/用户的UID为Firestore文档ID

service cloud.firestore {
  match /databases/{database}/documents {
    match /collection/{docId} {
      allow read, write: if request.auth != null && request.auth.uid == docId;
    }
  }
}

2/ 用户的 UID 存储在文档 ID 的一个字段中(例如:userId 字段)

service cloud.firestore {
  match /databases/{database}/documents {
    match /collection/{docId} {
      allow read: if request.auth != null && resource.data.userId == userId;
      allow write: if request.auth != null && request.resource.data.userId == userId;
    }     
  }
}

我只想在这里添加一些细节或示例。在此规则中,用户的 UID 存储为文档 ID。

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow read, write, delete: if request.auth != null && request.auth.uid == uid;
    }
    match /collection1/{document} {
        allow read: if request.auth != null;
    }
    match /collection2/{document} {
        allow read: if request.auth != null;
    }
  }
}

我在本地模拟器上做了一些测试代码:

firebase.firestore().doc('/users/'+user.uid).get().then(() => {
                console.log("user self path granted")
            }).catch(() => console.log("user other path deny"));
            
firebase.firestore().doc('/users/other').get().then(() => {
                console.log("user other path granted")
            }).catch(() => console.log("user other path deny"));
            
firebase.firestore().doc('/collection1/tCa4m3nGNjX4s3i1Uvc7').get().then(() => {
                console.log("collection1 path granted")
            }).catch(() => console.log("collection1 path deny"));
            
firebase.firestore().doc('/collection2/tCa4m3nGNjX4s3i1Uvc7').get().then(() => {
                console.log("collection2 path granted")
            }).catch(() => console.log("collection2 path deny"));
            
firebase.firestore().doc('/collection3/OvGk404uSdMFQAwN1qoA').get().then(() => {
                console.log("collection3 path granted")
            }).catch(() => console.log("collection3 path deny"));

输出

user self path granted
user other path deny
collection1 path granted
collection2 path granted
collection3 path deny