開始使用 Cloud Firestore 安全性規則

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

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

安全性規則第 2 版

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

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

撰寫規則

您將編寫及管理 Cloud Firestore Security Rules,這些函式會根據您為預設資料庫和專案中每個額外資料庫建立的資料模型量身打造。

所有 Cloud Firestore Security Rules 都包含 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 管理 REST API。

更新 Cloud Firestore Security Rules 最多可能需要一分鐘,才會影響新的查詢和監聽器。不過,變更最多可能需要 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 Storage 的安全性

您的應用程式將可運用 Cloud Firestore 的強大資料庫功能,以及 Cloud Storage 的檔案儲存和管理功能。這些產品搭配使用時,還能強化應用程式安全性,因為 Cloud Firestore 可擷取授權需求,供 Firebase 安全性規則用於這兩項產品。詳情請參閱Cloud Storage指南

後續步驟