借助 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 移動/Web 客戶端庫的每個數據庫請求都會根據您的安全規則進行評估。如果規則拒絕訪問任何指定的文檔路徑,則整個請求將失敗。
以下是基本規則集的一些示例。雖然這些規則有效,但不建議將它們用於生產應用程序:
需要授權
// 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 部分中的規則選項卡。
在在線編輯器中編寫您的規則,然後點擊發布。
使用 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
增強雲存儲的安全性
您的應用將受益於 Cloud Firestore 強大的數據庫功能以及 Cloud Storage 的文件存儲和管理功能。結合使用,這些產品還可以增強應用程序安全性,因為 Cloud Firestore 可以捕獲 Firebase 安全規則可用於這兩種產品的授權要求。有關更多信息,請參閱雲存儲指南。