【问题标题】:Unable to match request.auth.id with document id in Firestore rules无法将 request.auth.id 与 Firestore 规则中的文档 ID 匹配
【发布时间】:2019-11-07 12:24:08
【问题描述】:

我正在使用 Flutter 开发应用程序。我在 Firestore 上有一个数据库,其结构为:Users/(UserID)/collection/document 这里 UserID 是创建 (UserID) 文档的用户的唯一 uid。 获取用户uid的代码是

user.uid;

其中 user 是 FirebaseUser 的一个实例。 我正在尝试设置规则,只有当 request.auth.uid 与(UserID)文档 id 匹配时,才只有用户可以读/写。

service cloud.firestore {
  match /databases/{database}/documents {
    match /Users/{documentID} {
      allow read, write: if isOwner(documentID);
    }

    function isOwner(documentID){
        return request.auth.uid == documentID;
    }
  }
}

但是我遇到了这个错误

失败:状态{code=PERMISSION_DENIED, description=缺少或权限不足。, cause=null}

这是执行查询的代码。

class EmployeeList extends StatefulWidget {
  static bool isMale;
  final String userId;
  EmployeeList([this.userId]);
  void setIsMale(bool gen) {
    isMale = gen;
  }

  bool get getIsMale => isMale;

  @override
  State<StatefulWidget> createState() => _EmployeeList();
}

class _EmployeeList extends State<EmployeeList> {
  String employeeName;

  final TextEditingController textEditingController = 
TextEditingController();
  String gender;
  int keyIndex;
  CollectionReference listColRef;
  bool firstTime;
  Firestore db = Firestore.instance;

  @override
  void initState() {
    gender = EmployeeList().getIsMale ? "Male" : "Female";
    listColRef = 
db.collection('Users').document(widget.userId).collection('EmployeeList');
    print(widget.userId);
    super.initState();
  }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
         title: Text('Employees'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(5),
        child: StreamBuilder<QuerySnapshot>(
            stream: listColRef.where('Gender', isEqualTo: 
        gender).snapshots(),

这是数据库的结构:https://imgur.com/a/aI6UikO

【问题讨论】:

  • 请编辑问题以显示执行查询的代码无法按您预期的方式工作。
  • 你确定request uid和你的document id是一样的吗?默认情况下,身份验证用户和数据库用户不使用 firebase 链接。
  • 除了 Doug 要求的代码之外,我们可能还想查看您正在尝试阅读的文档。屏幕截图通常是最好的选择。
  • 链接Github repo可以吗?还是要我自己添加代码?
  • 这是数据库的结构。 imgur.com/a/aI6UikO

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


【解决方案1】:

您的数据库规则与您的查询不匹配。您的查询正在尝试使用模式/Users/{userId}/EmployeeList 在集合下查找文档。但是您的规则只允许访问/Users/{documentID} 下的文档。如果要允许访问嵌套子集合中的文档,则需要确保整个路径匹配。例如:

match /Users/{userId}/EmployeeList/{id} {
  allow read, write: if isOwner(userId);
}

【讨论】:

    猜你喜欢
    • 2020-06-10
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2021-09-11
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多