開始使用 Cloud Firestore 安全性規則

有了 Cloud Firestore 安全性規則,您就能專心打造優質的使用者體驗,不必費心管理基礎架構,也不必編寫伺服器端驗證和授權碼。

安全性規則採用簡單又明確的格式,提供存取權控管和資料驗證機制。如要建構以使用者為基礎的角色式存取系統,保護使用者資料的安全,您需要搭配使用 Firebase 驗證與 Cloud Firestore Security Rules。

安全性規則第 2 版

自 2019 年 5 月起,Cloud Firestore 安全性規則第 2 版現已上線。第 2 版規則會變更遞迴萬用字元 {name=**} 的行為。如果您打算使用集合群組查詢,必須使用版本 2。您必須將 rules_version = '2'; 加入安全性規則的第一行程式碼,選擇採用第 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 控制台

如要設定及部署第一組規則,請針對專案中的預設資料庫,開啟 Firebase 控制台 Cloud Firestore 專區的「Rules」分頁

請在線上編輯器中編寫規則,然後按一下「發布」

使用 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 指南

後續步驟