Firestore:userId规则

问题描述 投票:0回答:2

我不能让这个firestore规则起作用。

我想写/读到user-read-only/USER-ID-HERE/business/settings

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

    match /user-read-only/{userId} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;

      match /{document=**} {
        allow read, update, delete: if request.auth.uid == userId;
        allow create: if request.auth.uid != null;
      }
    }
  }
}

我继续得到消息

FirebaseError:权限丢失或不足。

我已经尝试了很多不同的方法与模拟器,他们都很成功,但我无法从我的应用程序重新生成。


  • 上面看起来有什么不对吗?
  • 以上可以简化吗?我希望用户能够控制{userId}以外的所有内容
  • 我怎么知道request.auth.uiduserId是否正常填充?

这有效

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

    match /{userId}/{document=**} {
      allow read, write;
    }
  }
}

这不起作用

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

    match /{userId}/{document=**} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}
firebase google-cloud-firestore firebase-security-rules
2个回答
1
投票

更新您的评论后“意图是扩展规则,以便用户可以管理{userId}以外的任何内容”:

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

    match /user-read-only/{userId}/{document=**} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;

    }
  }
}

请注意,create规则(从您的问题复制)允许任何经过身份验证的用户在任何{userId}文件夹下写入。


(相反,如果您只想为business/settings子集合和doc声明规则),以下应该可以解决问题:

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

    match /user-read-only/{userId}/business/settings {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;

    }
  }
}

为了确保正确填充userId,您可以在创建时将其作为字段添加到文档中,并检查create的规则是否正确,如下所示:

allow create: if request.auth.uid != null && request.auth.uid == request.resource.data.userId;

另一方面,Firebase Auth将自动确保正确填充request.auth.uid

最后,您可以观看Firebase团队关于安全规则的非常好的视频:https://www.youtube.com/watch?v=eW5MdE3ZcAw


这是用于测试的HTML页面。只需使用不同的用户ID更改userId的值即可。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
    <script src="https://www.gstatic.com/firebasejs/5.9.3/firebase.js"></script>

    <script>
      // Initialize Firebase
      var config = {
        apiKey: 'xxxxx',
        authDomain: 'xxxxx',
        databaseURL: 'xxxxx',
        projectId: 'xxxxx'
      };
      firebase.initializeApp(config);

      firebase
        .auth()
        .signInWithEmailAndPassword('[email protected]', 'yyyyyyy')
        .then(userCredential => {

          const userId = userCredential.user.uid;
          // Replace with another userId to test
          //e.g. const userId = 'l5Wk7UQGRCkdu1OILxHG6MksUUn2';

          firebase
            .firestore()
            .doc('user-read-only/' + userId + '/business/settings4')
            .set({ tempo: 'aaaaaaa' })
            .then(() => {
              return firebase
                .firestore()
                .doc(
                  'user-read-only/' + userId + '/testC/1/collec/2'
                )
                .get();
            })
            .then(function(doc) {
              if (doc.exists) {
                console.log('Document data:', doc.data());
              } else {
                // doc.data() will be undefined in this case
                console.log('No such document!');
              }
            })
            .catch(function(error) {
              console.log('Error getting document:', error);
            });
        });
    </script>
  </head>

  <body>
  </body>
</html>

1
投票

您是否部署了安全规则?

见:https://firebase.google.com/docs/firestore/security/get-started#deploying_rules

在从移动应用程序开始使用Cloud Firestore之前,您需要部署安全规则。您可以在Firebase控制台中或使用Firebase CLI部署规则。

您是否使用Firebase身份验证登录?

见:https://firebase.google.com/docs/firestore/security/rules-conditions

如果您的应用使用Firebase身份验证,则request.auth变量包含请求数据的客户端的身份验证信息。有关request.auth的更多信息,请参阅参考文档。

你怎么称呼Firestore方法?

看到:

像这样?

var userId = firebase.auth().currentUser.uid
var docRef = db.doc(`user-read-only/${userId}/business/settings`);

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

我认为你应该改变结构数据。

结构数据应该像db.collection('coll').doc('doc').collection('subcoll').doc('subdoc')

(Qazxswpoi)

所以{userId}应该是docId。不是收藏品。

安全规则应该是这个。

Collections->doc->SubCollections->SubDoc->SubSubCollections->SubSubDoc

设置集合ref是 match /databases/{database}/documents { match /users/{userId} { allow read, update, delete: if request.auth.uid == userId; allow create: if request.auth.uid != null; match /settings/{setting} { allow read, update, delete: if request.auth.uid == userId; allow create: if request.auth.uid != null; } } }

如果不起作用,那么您应该尝试基本规则集。

db.collection('users').doc(userId).collection('settings')
© www.soinside.com 2019 - 2024. All rights reserved.