安全规则使用入门

利用 Firestore 安全规则,您可以专注于打造良好的用户体验,而无需管理基础架构或编写服务器端身份验证和授权代码。

安全规则以简单明了的格式提供访问控制和数据验证。如需构建基于用户和基于角色的访问系统来确保用户的数据安全,您需要将 Firebase 身份验证与 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 移动/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=**} 路径可匹配整个数据库中的任何文档。继续阅读设计安全规则结构的指南,了解如何匹配特定数据路径及处理分层数据。

测试规则

Firestore 提供一个规则模拟器,可用于测试您的规则集。您可以从 Firebase 控制台的 Firestore 部分的规则标签页中访问模拟器。

通过规则模拟器,您可以模拟经过身份验证和未经身份验证的读取、写入和删除操作。模拟经过身份验证的请求时,您可以从各种提供程序构建并预览身份验证令牌。模拟的请求会针对编辑器中的规则集运行,而不针对您当前部署的规则集运行。

部署规则

您需要先部署安全规则,然后才可以开始从移动应用中使用 Firestore。您可以通过 Firebase 控制台、Firebase CLI 或 Firestore Management 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

后续步骤