首页 > 解决方案 > Firebase firestore 获取未经身份验证的用户文档

问题描述

我试图用 firebase 构建一个应用程序。我不想让用户对他/她进行 Firebase 身份验证。

我只希望他们使用他们的电话号码作为密码。这意味着他/她可以输入电话号码来查看他们的数据而无需身份验证。没有电话号码,他们无法读取数据。(也没有 OTP)。

现在我在 Firestore 规则中有这个,所以任何持有电话号码的人都可以查看数据。

 function isUserRef(field) { 
  return field in resource.data
    && resource.data.mobile == /customers/document/$(request.resource.data.mobile)
}

match /customers/{document=**} {
  allow read : if isUserRef(request.resource.data.mobile);
}

请求资源数据包含如下。

User{
"id" : null,
"mobile" : "7878445778"
}

但是上面的规则仍然不匹配基于他/她的手机号码的文件。我根本不想让用户进行身份验证。这是一个简单的应用程序,数据不是问题。

任何帮助表示赞赏!谢谢。

标签: firebasefluttergoogle-cloud-firestorefirebase-security

解决方案


目前尚不清楚您的数据库是如何设置的或您如何传递电话号码,但这里有一个更简单的方法可以帮助您指导。

设置您的数据库,其中电话号码是客户的 ID。如果这不可能,请创建一个phoneToCustomers用于将电话号码与客户匹配的集合。

示例 1:电话号码作为客户 ID

假设您的客户 ID 是他们的电话号码:

{
  "customers": {
    "7878445778": {...},
    "1231231234": {...}
  }
}

使用这个简单的规则,您可以完成您想要的:

match /customers/{phone} {

  // Allow anyone with the phone number to access this document
  allow get: if true;

  // Can't list all customers
  allow list: if false;
}

示例 2:客户 ID 查找表

假设您的数据库如下所示:

{
  "customers": {
    "abc123": {...},
    "xyz987": {...}
  },
  "phoneToCustomers": {
    "7878445778": "abc123",
    "1231231234": "xyz987"
  }
}

这些规则阻止用户查询您的客户或电话号码,但如果用户知道 ID,则允许检索文档。

match /customers/{customerId} {

  // Allow anyone with the customer ID to access this document
  allow get: if true;

  // Can't list all customers
  allow list: if false;
}

match /phoneToCustomers/{phone} {

  // Allow anyone with the phone number to access this document
  allow get: if true;

  // Can't list all customers
  allow list: if false;
}

然后,您需要 get()/phoneToCustomers/7878445778来获取客户 ID,然后需要第二个 get() 来检索客户数据/customers/<customerId>


推荐阅读