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