(Nuxtjs+ Firebase Firestore) FirebaseError: Missing or insufficient permissions

(Nuxtjs+ Firebase Firestore) FirebaseError: Missing or insufficient permissions

我使用 Nuxt.js + Firebase Firestore,我尝试从名称为 TestCollection 的集合中获取数据,但显示

Error getting document: FirebaseError: Missing or insufficient permissions.

我的本地主机显示这个。

Error getting document: FirebaseError: Missing or insufficient permissions.
    at new n (prebuilt-306f43d8-45d6f0b9.js?a6a6:188)
    at eval (prebuilt-306f43d8-45d6f0b9.js?a6a6:10426)
    at eval (prebuilt-306f43d8-45d6f0b9.js?a6a6:10427)
    at n.onMessage (prebuilt-306f43d8-45d6f0b9.js?a6a6:10449)
    at eval (prebuilt-306f43d8-45d6f0b9.js?a6a6:10366)
    at eval (prebuilt-306f43d8-45d6f0b9.js?a6a6:10397)
    at eval (prebuilt-306f43d8-45d6f0b9.js?a6a6:15160)
    at eval (prebuilt-306f43d8-45d6f0b9.js?a6a6:15218)

这里是调用集合的方法

async testPost(){
      try{
         await this.$fire.firestore.collection('TestCollection').get()
          .then((docs) => {
            console.log('docs:', docs)
          if (docs) {
            docs.forEach((doc) => {
              console.log(doc.data())
            })
          } else {
            console.log('No such document!')
          }
        }).catch((error) => {
          console.log('Error getting document:', error)
        })
      }catch (err){
        console.log(err)
      }
    },

在nuxt.config.js

modules: [
    // https://go.nuxtjs.dev/axios
    '@nuxtjs/axios',
    ['@nuxtjs/firebase', {
      config: {
        apiKey: process.env.FIREBASE_API_KEY,
        authDomain: process.env.FIREBASE_AUTH_DOMAIN,
        projectId: process.env.FIREBASE_PROJECT_ID,
        storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
        messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
        appId: process.env.FIREBASE_APP_ID,
        measurementId: process.env.FIREBASE_MEASUREMENT_ID,
      },

      services: {
        firestore: true,
        storage: true,
        database: true,
      },
    }],
  ],

在database.rules.json

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "false"
      }
    },
    "cases": {
      ".read": true
    }
  }
}

在filetore.rules

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

您的安全规则不允许任何人从 Firestore 读取任何数据:

match /{document=**} {
  allow read, write: if false;
}

因此,您尝试从数据库中读取数据的代码被这些规则拒绝的事实是按预期工作的。

这些是默认规则,因此我强烈建议阅读有关 Firestore specifically and for Firebase overall.

保护数据库的文档

您需要从对允许您的代码运行的规则的最小更改开始,称为 principle of least privilege。鉴于您共享的代码,那将是:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
    match /TestCollection/{doc} {
      allow read: if true;
    }
  }
}

所以现在我们允许世界上任何人阅读整个 TestCollection,因为您的代码似乎就是这样做的,但我们仍然不允许所有其他操作。