開始使用安全性規則

有了 Firestore Security Rules,您就能專心打造優質的使用者體驗,不必管理基礎架構,也不用編寫伺服器端驗證和授權程式碼。

安全性規則提供簡單但富有表現力的格式,可控管存取權及驗證資料。如要建構以使用者和角色為基礎的存取系統,確保使用者資料安全無虞,您必須搭配使用 Firebase Authentication 和 Firestore 安全性規則。

安全性規則第 2 版

自 2019 年 5 月起,Firestore 安全性規則第 2 版已推出。規則第 2 版會變更遞迴萬用字元 {name=**} 的行為。如要使用集合群組查詢,請務必使用第 2 版。您必須在安全規則中加入 rules_version = '2'; 做為第一行,才能選擇採用第 2 版:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

撰寫規則

您將撰寫及管理 Firestore 安全性規則,這些規則會根據您為專案中預設資料庫和每個額外資料庫建立的資料模型進行調整。

所有 Firestore 安全性規則都包含 match 陳述式 (用於識別資料庫中的文件) 和 allow 運算式 (用於控管這些文件的存取權):

service cloud.firestore {
  match /databases/{database}/documents {
    match /<some_path>/ {
      allow read, write: if <some_condition>;
    }
  }
}

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=**} 路徑會比對整個資料庫中的任何文件。請繼續參閱安全規則結構指南,瞭解如何比對特定資料路徑及處理階層式資料。

測試規則

Firestore 提供規則模擬器,可供您測試規則集。您可以在 Firebase 控制台的 Firestore 區段中,透過「規則」分頁標籤存取模擬器。

規則模擬器可模擬已驗證和未驗證的讀取、寫入和刪除作業。模擬已驗證的要求時,您可以建構及預覽來自各種供應商的驗證權杖。模擬要求會針對編輯器中的規則集執行,而非目前部署的規則集。

部署規則

您必須先部署安全性規則,才能從行動應用程式開始使用 Firestore。您可以在 Firebase 控制台中部署規則、使用 Firebase CLI,或透過 Firestore 管理 REST API 部署規則。

更新 Firestore 安全性規則後,最多需要一分鐘才會影響新的查詢和監聽器。不過,變更最多可能需要 10 分鐘才會全面生效,並影響所有有效監聽器。

使用 Firebase 控制台

如要設定及部署第一組規則,請在 Firebase 控制台的 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

後續步驟