[英]Firebase Security Rules to specific Collection?
我有三个 collections, Collect 1
和Collection 2
,只能由经过身份验证的用户读取。 第三个集合是Users
,只有经过身份验证的用户才能读取、写入、更新和删除,但只能读取具有各自 UID 的文档。 当前规则适用于所有集合。 当前的安全规则是:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if request.auth != null;
}
}
}
我只想在这里添加一些细节或示例。 在此规则中,用户的 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"));
Output
user self path granted
user other path deny
collection1 path granted
collection2 path granted
collection3 path deny
只有经过身份验证的用户才能读取、写入、更新和删除,但只有具有各自 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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.