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