Firebase 🔥 的安全规则,特别是 Cloud Firestore 的,用于控制对数据库的访问。它们定义了谁可以读取、写入和修改数据。以下是如何配置安全规则来保护你的 Firestore 数据库:
Firestore 安全规则基于以下结构:
service cloud.firestore {
match /databases/{database}/documents {
match /collection/{document} {
allow read: if ;
allow write: if ;
}
}
}
service cloud.firestore: 指定规则适用于 Cloud Firestore。match /databases/{database}/documents: 匹配数据库中的所有文档。match /collection/{document}: 匹配特定的集合和文档。 {document} 是一个通配符,可以匹配任何文档 ID。allow read: if : 定义读取数据的条件。allow write: if : 定义写入数据的条件。只允许认证用户读取数据:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if request.auth != null;
allow write: if false;
}
}
}
这个规则允许任何已认证的用户读取任何文档,但禁止所有写入操作。
允许用户读取和写入自己的文档:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
这个规则允许用户读取和写入 /users/{userId} 集合中与他们的 UID 匹配的文档。 request.auth.uid 包含当前用户的 UID。
限制对特定字段的写入:
service cloud.firestore {
match /databases/{database}/documents {
match /posts/{postId} {
allow read: if true;
allow update: if request.auth != null && request.auth.uid == resource.data.authorId;
allow create: if request.auth != null && request.auth.uid == request.resource.data.authorId;
}
}
}
这个规则允许任何人读取帖子,但只允许帖子的作者更新它。它也只允许作者创建帖子。 resource.data 包含数据库中现有文档的数据,而 request.resource.data 包含请求中要写入的数据。
你可以定义函数来重用规则逻辑:
service cloud.firestore {
function isSignedIn() {
return request.auth != null;
}
function isOwner(resource) {
return request.auth.uid == resource.data.userId;
}
match /databases/{database}/documents {
match /items/{itemId} {
allow read: if isSignedIn();
allow write: if isSignedIn() && isOwner(resource);
}
}
}
这个例子定义了两个函数 isSignedIn() 和 isOwner(),使规则更具可读性。
可以使用 request.resource.data 验证传入的数据:
service cloud.firestore {
match /databases/{database}/documents {
match /messages/{messageId} {
allow create: if request.auth != null
&& request.resource.data.keys().hasAll(['text', 'timestamp', 'authorId'])
&& request.resource.data.text is string
&& request.resource.data.timestamp is number
&& request.resource.data.authorId == request.auth.uid;
}
}
}
这个规则验证新消息是否包含 text、timestamp 和 authorId 字段,以及 text 是否是字符串,timestamp 是否是数字,并且 authorId 是否与用户的 UID 匹配。
通配符 ({document}): 匹配单个文档 ID。
递归通配符 ({document=**}): 匹配任何深度的文档路径。
service cloud.firestore {
match /databases/{database}/documents {
match /groups/{groupId}/{document=**} {
allow read: if request.auth != null;
allow write: if false;
}
}
}
这个规则允许认证用户读取 /groups/{groupId} 集合及其所有子集合中的任何文档。
使用 Firebase 控制台中的规则模拟器来测试你的规则。你可以模拟不同的用户和数据,并查看规则如何评估。
将规则部署到你的 Firestore 数据库,使其生效。 可以在 Firebase 控制台中完成此操作。
记住,安全规则是保护你的 Firestore 数据库的关键。花时间设计和实施健全的规则,以确保数据的安全和完整性。 🔐