Firestore 是 Google Cloud 提供的 NoSQL 文档型数据库,安全规则对于保护数据访问至关重要。合理配置规则,可以防止未授权的读写操作,保证数据安全性与隐私性。以下内容将帮助你快速上手并配置适合你的 Firestore 安全规则。
service cloud.firestore {
match /databases/{database}/documents {
// 数据库下所有文档规则
}
}
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
解释:只有通过 Firebase Authentication 登录的用户才可以读写任意文档。
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
allow write: if false;
}
}
}
解释:任何人都可以读取,但任何人都不能写入数据。
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
}
}
}
解释:用户只能访问自己的 user 文档,而无法操作其他用户的数据。
service cloud.firestore {
match /databases/{database}/documents {
match /posts/{postId} {
allow update, delete: if request.auth.uid == resource.data.authorId;
allow create: if request.auth.uid != null;
allow read: if true;
}
}
}
解释:仅作者本人可修改、删除帖子;任何已登录用户可创建;所有人可阅读。
通过 {document=**} 可以匹配所有嵌套文档或子集合,方便全局设定。
if true),但正式上线必须加严!通过合理配置 Firestore 安全规则,可以有效保障数据的机密性与完整性。务必针对不同应用场景采取最小权限原则,及时修订并测试规则,打造安全可靠的云端数据环境!💪