【问题标题】:Add notAuthenticated() security rule for Firestore database collection为 Firestore 数据库集合添加 notAuthenticated() 安全规则
【发布时间】:2021-09-27 12:50:40
【问题描述】:

我需要为没有身份验证的文档集合添加一个匹配数据库。这样做的正确方法是什么? 这是当前的安全规则:

service cloud.firestore {
  match /databases/{database}/documents {
  function authenticated() { return request.auth.uid != null }
  
    match /users/{userId} {
       allow get: if authenticated() && request.auth.uid == userId;
       allow create: if authenticated() && request.auth.uid == userId;
       allow update, delete: if authenticated() && request.auth.uid == userId;
    }

    match /users/{userId}/products/{productId} {
      allow get: if authenticated() && request.auth.uid == userId;
            allow list: if authenticated() && request.auth.uid == userId;
      allow create: if authenticated() && request.auth.uid == userId;
      allow update, delete: if authenticated() && request.auth.uid == userId;
    }
  }
}

我尝试添加此内容,但仍然收到 Firestore 权限不足错误

    function notAuthenticated() {
      return request.auth == null;
    }
    
    match /share/{id}/documents {
 allow get:  if notAuthenticated();     
 allow create:  if notAuthenticated();
 allow read:  if notAuthenticated();

这是向 Firestore 添加“共享”的 JS 代码。:

  const db = firebase.firestore()
  const docRef = db.collection('share').doc(val)

  docRef
    .get()
    .then(doc => {
      if (doc.exists) {
        console.log('Document data:', doc.data().id)
      } else {
      
        console.log('No such document!')
      }
    })
    .catch(error => {
      console.log('Error getting document:', error)
    })
enter code here

【问题讨论】:

  • “我仍然收到 Firestore 权限不足错误:”您能显示重现此错误的代码吗?特别是那里:您可以登录firebase.auth().currentUser 以表明它是null,因为这是您的安全规则所要求的。

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


【解决方案1】:

您当前的代码仅允许未登录 Firebase 身份验证的用户使用。因此它拒绝来自已登录用户的操作。

听起来您希望任何人都能够阅读该特定集合,无论他们是否已登录 Firebase 身份验证。

最简单的规则是:

match /share/{id}/documents {
  allow get: if true;
  allow create: if true;
  allow read: if true;

在这种情况下,我绝对建议在 create 规则中添加一些验证,就像上面一样,任何人都可以编写(这是你想要的)他们觉得(你可能不想要的)任何数据你的数据库。

【讨论】:

  • 感谢您的回答和推荐。这是否足以验证创建规则? if id.length >4 && id.length <20(只允许写短字符串)
  • 除了您之外,任何人都无法确定什么是足够的,但该规则确实会检查新文档 ID 的长度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2021-07-14
  • 1970-01-01
  • 2019-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多