開始使用 Cloud Firestore 安全規則

借助 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 安全規則。

所有 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 CLI 或 Cloud Firestore 管理 REST API 在 Firebase 控制台中部署規則。

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 rules for all configured databases
firebase deploy --only firestore

增強雲存儲的安全性

您的應用程序將受益於 Cloud Firestore 強大的數據庫功能以及 Cloud Storage 的文件存儲和管理功能。一起使用時,這些產品還可以增強應用程序安全性,因為 Cloud Firestore 可以捕獲兩種產品的 Firebase 安全規則可使用的授權要求。更多信息請參見雲存儲指南

下一步