Firestore 规则不允许读取给定的有效 UID

时间:2021-07-13 19:34:19

标签: javascript firebase google-cloud-firestore firebase-security

我编写了以下 firestore 规则,通过仅在调用者的 UID 与文档 ID 匹配时才允许请求来限制对用户集合的读取。用户集合的文档 ID 与 Firebase 身份验证中的 UID 之间存在奇偶校验。

    function isAuthenticated() {
      return request.auth.uid != null;
    }

    // Users collection
    match /users/{userId} {
      allow read: if isAuthenticated() 
        && request.auth.uid == userId;
    }

我在集合中有一个 ID 为 Eli90wRvWkfKcOfn1C4DBDqxQTz1 的文档。当使用相同的身份验证用户点击 firestore 时,我收到以下错误:

Failed read with uid check

如果我取消对 request.auth.uid == userId 的检查,则会生成此规则并成功读取:

    // Users collection
    match /users/{userId} {
      allow read: if isAuthenticated();
    }

enter image description here

正在调用的查询是:

export const getUser = (uid: string) => {
  return db.collection('users').where('id', '==', uid).limit(1).get();
};

我看到很多人在他们的规则中使用 UID 检查,但为什么在我的情况下不起作用?

1 个答案:

答案 0 :(得分:1)

您的安全规则与此代码匹配:

db.collection('users').doc(uid).get();

所以这里我们访问单个特定的文档,文档 ID 是用户的 UID。


如果您想在文档的某个字段中查询 UID,您可以使用以下规则进行保护:

match /users/{doc} {
  allow read: if resource.data.id === request.auth.uid;
}

所以现在规则匹配您的原始代码,并且只允许读取 uid 字段的值与当前用户的 uid 匹配的文档。

相关问题