首页 > 解决方案 > 无法将 request.auth.id 与 Firestore 规则中的文档 ID 匹配

问题描述

我正在用 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,描述=缺少或权限不足。,原因=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

标签: fluttergoogle-cloud-firestorefirebase-security

解决方案


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

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

推荐阅读