【问题标题】:Privatize cloud firestore database using rules and authentication使用规则和身份验证私有化 Cloud Firestore 数据库
【发布时间】:2018-05-31 02:03:00
【问题描述】:

我正在为 firebase 的云 Firestore 编写规则,并且我想使用用户的身份验证 ID 来限制对数据库的访问,但这些规则的行为与我预期的不同。

所以,我的数据库结构是这样的:

/users/{userId}/groups/{groupId}

我只希望用户只能使用他们自己的 userId 访问文档。

为此,我编写了如下规则:

service cloud.firestore {
  match /databases/{database}/documents {

    match /users/{userId=**} {
        allow read: if userId == request.auth.uid;
    }

  }
}

但是有了这个,我的用户无法从数据库中读取他们自己的“组”。

我正在使用 javascript,检索“组”的代码如下:

console.log("uid: ", uid)
db.collection("users/" + uid + "/groups")
  .onSnapshot(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
      console.log(doc.data())
    })
})

现在由于云火库没有像实时数据库那样好的调试工具,我自己做了一点调试。

我有一个 uid 为“5lS2NA21UgbabEw4AkyWyef9FH42”的测试用户,所以我更改了这样的规则:

service cloud.firestore {
  match /databases/{database}/documents {

    match /users/{userId=**} {
        allow read: if "5lS2NA21UgbabEw4AkyWyef9FH42" == request.auth.uid;
    }

  }
}

有了这个,我的测试用户能够成功地从他的文档中检索“组”数据(当然所有其他用户都不能,但是)。

现在我将规则更改为:

service cloud.firestore {
  match /databases/{database}/documents {

    match /users/{userId=**} {
        allow read: if "5lS2NA21UgbabEw4AkyWyef9FH42" == userId;
    }

  }
}

现在我无法从数据库中获取任何数据。

谁能告诉我我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    我想我已经弄清楚了。问题是这个 {userId=**}

    如果你有以下规则

    service cloud.firestore {
      match /databases/{database}/documents {
    
        match /users/{userId=**} {
            allow read: if userId == request.auth.uid;
        }
    
      }
    }
    

    并且正在尝试访问用户/5lS2NA21UgbabEw4AkyWyef9FH42/组,“userId”变量不会评估为 5lS2NA21UgbabEw4AkyWyef9FH42(我不知道它会是什么,但我猜是“5lS2NA21UgbabEw4AkyWyef9FH42/组”)。所以如果你想私有化文档,你必须在规则中指定每个文档,如下所示。

    service cloud.firestore {
      match /databases/{database}/documents {
    
        match /users/{userId} {
            match /groups/{groupId} {
               allow read: if userId == request.auth.uid;
            }
            match /events/{eventId} {
               allow read: if userId == request.auth.uid;
            }
        }
    
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 2020-09-24
      • 2018-04-04
      • 2019-07-15
      • 2020-06-20
      • 2019-10-17
      • 2021-07-23
      • 1970-01-01
      相关资源
      最近更新 更多