首页 > 解决方案 > Android 应用的 Firestore 安全设置应该是什么?

问题描述

我刚刚创建了我的第一个Android应用程序Kotlin作为FIrestore数据库,我也使用了电话身份验证。创建数据库时,我使用了测试模式,现在我想将我的应用程序上传到 Google Play,以便公众可以开始使用我的应用程序。我应该考虑更改的 Firestore 的安全设置是什么?请对此提出一些建议。

目前,这是“规则”选项卡下的内容。

    rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if
          request.time < timestamp.date(2021, 8, 29);
    }
  }
}

标签: androidfirebasegoogle-cloud-firestorefirebase-security

解决方案


根据我从评论中的示例中了解到的情况,您有 7 个集合(示例)A、B、C、P、Q、Y 和 Z。

收藏 可以通过
甲、乙、丙 某些用户
磷,问 通过电话身份验证的用户
Y, Z 某些用户
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /A/{docId} {
      allow read, write: if isCertainUser();
    }
    // Same rule for B and C

    match /P/{docId} {
      allow read, write: if request.auth != null && request.auth.token.firebase.sign_in_provider == "phone";
    }
    // Same rule for Q
    // Checks if user is logged in by Phone auth

    match /Y/{docId} {
      allow read, write: if isCertainUser();
    }
    // Same rule for Z
  }
}

您必须编写一个函数isCertainUser才能使规则起作用。现在有多种方法可以指定用户具有访问权限。例如,您可以添加管理员自定义声明或将可以访问该集合的用户的文档存储在单独的集合中,并检查请求数据的用户文档是否存在于该白名单集合中。

match /A/{docId} {
  allow read: if request.auth != null && exists(/databases/$(database)/documents/whitelisted/$(request.auth.uid));
}

此规则将允许用户读取集合 A 中的数据,仅当“白名单”集合中存在以用户 UID 作为文档键的文档时。

参考:

Cloud Firestore 安全规则的编写条件

request.auth 的接口


推荐阅读