要在 Firebase 控制台中快速测试更新后的 Firebase 安全规则,请使用规则测试平台。
规则测试平台是一种方便的工具,可用于探索新的行为或者在您创建规则时快速验证这些规则。它会显示一条消息,根据您为模拟设置的参数确认允许还是拒绝访问。
使用规则测试平台
- 打开 Firebase 控制台,然后选择您的项目。
- 然后,在产品导航中执行以下操作之一:
- 根据需要选择 Realtime Database、Cloud Firestore 或 Storage,然后点击规则以导航到规则编辑器。
- 完成修改后,点击编辑器中的规则测试平台。
- 在“规则测试平台”设置中,选择用于测试的选项,包括:
- 测试读取或写入。
- 数据库或存储分区中的特定位置(以路径表示)。
- 身份验证类型 - 未经身份验证、经过身份验证的匿名用户或特定用户 ID
- 您的规则特别引用的文档专属数据(例如,如果您的规则要求必须存在特定字段才允许执行写入操作)
- 点击运行,然后在编辑器上方的横幅中查看结果。
示例规则测试平台使用场景
使用以下示例场景和基本规则测试规则测试平台行为。
Cloud 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
}
}
}
Realtime Database
// 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" } } } }
Storage
// 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 详细信息,您应该看到一个横幅,确认已成功允许或拒绝读取操作。