快速验证 Firebase 安全规则

如需在 Firebase 控制台中快速测试更新后的 Firebase Security Rules,请使用规则测试平台。

使用 Rules Playground,您可以方便地探索新的行为或在您编写规则时进行快速验证。该平台会显示一条消息,根据您为模拟设置的参数确认是允许还是拒绝访问。

使用 Rules Playground

  1. 打开 Firebase 控制台,然后选择您的项目。
  2. 然后,在产品导航栏中执行以下任一操作:
    • 根据需要选择 Realtime DatabaseCloud FirestoreStorage,然后点击规则以导航到 Rules 编辑器。
  3. 完成修改后,点击编辑器中的 Rules Playground
  4. 在“Rules Playground”设置中,选择用于测试的选项,包括:
    • 测试读取或写入。
    • 数据库或存储桶中的特定位置(以路径表示)。
    • 身份验证类型 - 未经身份验证、经过身份验证的匿名用户或特定用户 ID。
    • 您的规则特别引用的文档专属数据(例如,如果您的规则要求必须存在特定字段才允许执行写入操作)。
  5. 点击运行,然后在编辑器上方的横幅中查看结果。

示例 Rules Playground 使用场景

使用以下示例场景和基本规则,对 Rules Playground 的行为进行测试。

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"  }  }  }  }  

Cloud Storage

// Grants a user access to a node matching their user ID service firebase.storage {  match /b/{bucket}/o {  // Files look like: "user/<UID>/file.txt"  match /user/{userId}/{fileName} {  allow read, write: if request.auth != null && request.auth.uid == userId;  }  } } 
  • Rules 编辑器中,添加给定的规则。

  • 模拟类型下拉菜单中选择获取,然后在位置字段中输入一个有效的路径。

  • 启用身份验证,并从提供方下拉菜单中选择一个身份验证类型。

  • 输入用户 ID 详细信息,并点击运行

模拟结果显示在编辑器的顶部。根据您输入的用户 ID 详细信息,您应该会看到一个横幅,确认已成功允许或拒绝读取操作。