要在 Firebase 控制台中快速测试更新后的 Firebase 安全规则,请使用 Rules Playground。
当您探索新行为或在编写规则时快速验证规则时,Rules Playground 是一个方便的工具。它会显示一条消息,确认根据您为模拟设置的参数允许或拒绝访问。
使用规则游乐场
- 打开Firebase 控制台并选择您的项目。
- 然后,从产品导航中执行以下操作之一:
- 根据需要选择Realtime Database 、 Cloud Firestore或Storage ,然后单击Rules以导航到 Rules 编辑器。
- 完成编辑后,单击编辑器中的Rules Playground 。
- 在Rules Playground设置中,为您的测试选择选项,包括:
- 测试读取或写入。
- 数据库或存储桶中的特定位置,作为路径。
- 身份验证类型 — 未经身份验证、经过身份验证的匿名用户或特定用户 ID。
- 您的规则特别引用的文档特定数据(例如,如果您的规则要求在允许写入之前存在特定字段)。
- 单击运行并在编辑器上方的横幅中查找结果。
示例规则游乐场场景
使用以下示例场景和基本规则测试 Rules Playground 行为。
云端 Firestore
service cloud.firestore {
match /databases/{database}/documents {
// Allow only authenticated content owners access
match /some_collection/{document} {
allow read, write: if request.auth != null && request.auth.uid == request.resource.data.author_uid
}
}
}
实时数据库
// These rules grant access to a node matching the authenticated // user's ID from the Firebase auth token { "rules": { "users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid" } } } }
云储存
// Grants a user access to a node matching their user ID
service firebase.storage {
match /b/{bucket}/o {
// Files look like: "user/<UID>/path/to/file.txt"
match /user/{userId}/{allPaths=**} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
在规则编辑器中,添加上面给出的规则。
从模拟类型下拉菜单中选择获取,然后在位置字段中输入有效路径。
切换身份验证并从提供商下拉列表中选择一种身份验证类型。
输入用户 ID 详细信息并单击运行。
模拟的结果出现在编辑器的顶部。根据您输入的用户 ID 详细信息,您应该会看到一个横幅,确认读取已被成功允许或拒绝。