Catch up on highlights from Firebase at Google I/O 2023. Learn more

快速驗證 Firebase 安全規則

要在 Firebase 控制台中快速測試更新後的 Firebase 安全規則,請使用規則園地。

規則遊樂場是一個方便的工具,可以在您探索新行為或在編寫規則時快速驗證規則時使用。它會顯示一條消息,確認根據您為模擬設置的參數允許或拒絕訪問。

使用規則遊樂場

  1. 打開Firebase 控制台並選擇您的項目。
  2. 然後,從產品導航中執行以下操作之一:
    • 根據需要選擇Realtime DatabaseCloud FirestoreStorage ,然後單擊Rules導航到規則編輯器。
  3. 完成編輯後,單擊編輯器中的Rules Playground
  4. 規則園地設置中,選擇測試選項,包括:
    • 測試讀取或寫入。
    • 數據庫或存儲桶中的特定位置,作為路徑。
    • 身份驗證類型 — 未經身份驗證、經過身份驗證的匿名用戶或特定用戶 ID。
    • 您的規則特別引用的文檔特定數據(例如,如果您的規則要求在允許寫入之前存在特定字段)。
  5. 單擊“運行”並在編輯器上方的橫幅中查找結果。

示例規則遊樂場場景

使用以下示例場景和基本規則測試規則遊樂場行為。

雲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 詳細信息,您應該會看到一個橫幅,確認讀取已成功允許或拒絕。