【问题标题】:firebase rule with cloud firestore使用 Cloud Firestore 的 firebase 规则
【发布时间】:2019-12-15 06:02:10
【问题描述】:

为 firebase 设置乘法规则。

以 3 个数据库集合为例。

Cloud Firestore

在国家/地区的 firebase 集合中,应允许所有用户读写。

在 firebase 收集汽车时,只允许管理员编写。

在飞机的 firebase 集合中,所有经过身份验证的用户都可以写入。

不工作的文档: https://firebase.google.com/docs/rules/basics#cloud-firestore

如何使用正确的语法设置规则?

    // All public to include countries
    service cloud.firestore {
       match /databases/{database}/documents {
         match /{document=**} {
           allow read: if true ; 
           allow write: if true ;
         }
       }

     // check cars collection
     match /databases/{database}/documents/Cars {
        // For attribute-based access control, Check a boolean `admin` attribute
        allow read: if true ;
        allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;

    }

     // check airplanes collection
      match /databases/{database}/documents/Airplanes {
        // Allow only authenticated content owners access
        match /{database}/{userId}/{documents=**} {
          allow read: if true ; 
          allow write: if request.auth.uid == userID
        }
      }
    }

【问题讨论】:

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


    【解决方案1】:

    你的规则有一些错误。

    1. 您有一个声明,允许每个人编写每个文档。当有多个 match 语句匹配当前请求,并且其中一个语句允许请求时,最终判定为 ALLOW。取下护套:
    match /{document=**} {
        allow read: if true ; 
        allow write: if true ;
    }
    
    1. Firestore 区分大小写。为避免错误,请使用一致的命名约定,例如 camelCase 或 pascal_case。

    2. 您必须在匹配语句的末尾添加一个文档匹配变量

    这应该可行:

    service cloud.firestore {
        match /databases/{database}/documents {
    
            match /users/{userId} {
                allow read: if true;
                allow write: if request.auth != null && request.auth.uid == userId;
            }
    
            match /cars/{carId} {
                allow read: if true ;
                allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;
            }
    
            match /airplanes/{airplane} {
                allow read: if true ; 
                allow write: if request.auth != null ;
            }
        }
    }
    

    【讨论】:

    • 感谢您的额外解释。如果我使用模拟器,它不再允许在飞机上匿名阅读。模拟器路径(我真的不明白路径入口的意义):/airplanes/Id1000(而Id1000是文档键)。
    • 抱歉,我又忘记了一件事。当您已经在数据库匹配块内时,您必须删除完整的数据库路径。所以你必须在match /databases/{database}/documents { 中用match /... 替换match /databases/{database}/documents/...。抱歉,我忘记了。
    猜你喜欢
    • 2021-06-13
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 2018-07-17
    • 2020-06-12
    • 2019-10-17
    • 2018-06-21
    • 2021-06-21
    相关资源
    最近更新 更多