借助 Cloud Firestore 安全規則,您可以專注於構建出色的用戶體驗,而無需管理基礎架構或編寫服務器端身份驗證和授權代碼。
安全規則以簡單而富有表現力的格式提供訪問控制和數據驗證。要構建基於用戶和基於角色的訪問系統以確保用戶數據的安全,您需要將Firebase 身份驗證與 Cloud Firestore 安全規則結合使用。
安全規則版本 2
自 2019 年 5 月起,Cloud Firestore 安全規則第 2 版現已推出。規則的第 2 版更改了遞歸通配符{name=**}
的行為。如果您計劃使用集合組查詢,則必須使用版本 2。您必須通過rules_version = '2';
安全規則的第一行:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
編寫規則
所有 Cloud Firestore 安全規則都包含match
語句,用於識別數據庫中的文檔,並allow
表達式,用於控制對這些文檔的訪問:
service cloud.firestore {
match /databases/{database}/documents {
match /<some_path>/ {
allow read, write: if <some_condition>;
}
}
}
在讀取或寫入任何數據之前,都會根據您的安全規則評估來自 Cloud Firestore 移動/網絡客戶端庫的每個數據庫請求。如果規則拒絕訪問任何指定的文檔路徑,則整個請求將失敗。
下面是一些基本規則集的示例。雖然這些規則是有效的,但不建議將它們用於生產應用程序:
需要授權
// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
全部拒絕
// Deny read/write access to all users under any conditions
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
允許全部
// Allow read/write access to all users under any conditions
// Warning: **NEVER** use this rule set in production; it allows
// anyone to overwrite your entire database.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
上面示例中使用的{document=**}
路徑匹配整個數據庫中的任何文檔。繼續閱讀構建安全規則的指南,了解如何匹配特定數據路徑和使用分層數據。
測試規則
Cloud Firestore 提供了一個規則模擬器,您可以使用它來測試您的規則集。您可以從 Firebase 控制台的 Cloud Firestore 部分的“規則”選項卡訪問模擬器。
規則模擬器允許您模擬經過身份驗證和未經身份驗證的讀取、寫入和刪除。當您模擬經過身份驗證的請求時,您可以構建和預覽來自各種提供者的身份驗證令牌。模擬請求針對您編輯器中的規則集運行,而不是您當前部署的規則集。
部署規則
在您開始通過移動應用使用 Cloud Firestore 之前,您需要部署安全規則。您可以在 Firebase 控制台中或使用 Firebase CLI 部署規則。
Cloud Firestore 安全規則的更新可能需要一分鐘的時間來影響新的查詢和偵聽器。但是,最多可能需要 10 分鐘才能完全傳播更改並影響任何活動的偵聽器。
使用 Firebase 控制台
要設置和部署您的第一組規則,請在 Firebase 控制台的 Cloud Firestore 部分中打開規則選項卡。
在在線編輯器中編寫您的規則,然後單擊Publish 。
使用 Firebase CLI
您還可以使用Firebase CLI部署規則。使用 CLI 允許您使用應用程序代碼將規則置於版本控制之下,並將規則部署為現有部署過程的一部分。
// Set up Firestore in your project directory, creates a .rules file
firebase init firestore
// Edit the generated .rules file to your desired security rules
// ...
// Deploy your .rules file
firebase deploy --only firestore:rules