開始使用 Cloud Firestore 安全性規則

藉助 Cloud Firestore 安全性規則,您就能專心打造出色的使用者 不必管理基礎架構或編寫伺服器端程式碼 驗證和授權碼

安全性規則提供簡單而又簡單的存取權控管和資料驗證機制 表達出的意味建構以使用者和角色為基礎的存取系統, 使用者資料安全,您必須使用 Firebase 透過 Cloud Firestore 安全性規則進行驗證。

安全性規則第 2 版

自 2019 年 5 月起,Cloud Firestore 安全性規則第 2 版現已上線 廣告。規則第 2 版改變了遞迴性 萬用字元 {name=**}。如果您打算使用第 2 版 使用集合群組查詢。您必須選擇加入 版本 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 行動/網路用戶端程式庫發出的每項資料庫要求,評估是否符合條件 必須先監控安全性規則,再讀取或寫入任何資料如果規則拒絕存取 到任何指定的文件路徑,整個要求都會失敗。

以下列舉幾個基本規則組合的範例。雖然這些規則有效,但 不建議用於正式版應用程式:

需要驗證

// 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 Management REST API。

Cloud Firestore 安全性規則的更新作業最多可能需要一分鐘才會影響新的查詢,以及 接聽程式。不過,變更最多可能需要 10 分鐘才能全面生效 並影響任何有效的事件監聽器

使用 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 Storage 的安全性

您的應用程式將受益於 Cloud Firestore 強大的資料庫功能 以及 Cloud Storage 的檔案儲存和管理功能二手車 這些產品也能加強應用程式的安全性 Cloud Firestore 可以擷取 Firebase 安全性規則可使用的授權需求 。詳情請參閱 Cloud Storage 指南

後續步驟