【问题标题】:angular + firestore: how to allow public read access to a documentangular + firestore:如何允许对文档的公共读取访问
【发布时间】:2017-10-05 19:06:12
【问题描述】:

我是一名学生开发人员,在我的 Angular 应用中试用新的 Firestore,但遇到了安全规则。

我想要达到的目标:

使用模板绑定在角度视图中显示 Firestore 文档。该文档应该可供未经身份验证的用户查看。

问题:

如果未经身份验证的用户尝试查看该页面,则会发生权限错误:

ERROR 错误:权限缺失或不足。 在新的 FirestoreError (error.js:164)

模板文件:

<p>{{ (item | async)?.name }}</p>

component.ts 文件:

interface Profile {
   name: string;
}
...
private itemDoc: AngularFirestoreDocument<Profile>;
item: Observable<Profile>;
...
ngOnInit() {

   this.itemDoc = this.afs.doc<Profile>('profiles/0mlC8uWaKeArzk0sfIfX');
   this.item = this.itemDoc.valueChanges();
}

firestore 规则:

service cloud.firestore {
   match /databases/{database}/documents {
     match /{document=**} {
        allow read, write: if request.auth != null;
     }
   }
}

【问题讨论】:

    标签: angular firebase google-cloud-firestore


    【解决方案1】:

    如您所知,对 Cloud Firestore 数据的访问由 Security Rules 控制。当您收到“权限不足错误”时,这意味着您的读取或写入已被规则拒绝。

    在你的情况下,你有这些规则:

    service cloud.firestore {
       match /databases/{database}/documents {
         match /{document=**} {
            allow read, write: if request.auth != null;
         }
       }
    }
    

    大致翻译成英文,意思是“只要用户登录,就允许读取或写入数据库中的任何文档”。

    因此,如果您收到错误消息,则表示用户未登录 (request.auth == null)。

    所以你有两个选择:

    选项 1:向您的应用添加身份验证

    您可以将Firebase Authentication 添加到您的应用中。满足您的规则的最简单的事情是匿名身份验证:

    firebase.auth().signInAnonymously()
    .then(function() {
       // You're signed in, reads will work
    })
    .catch(function(error) {
      // Handle Errors here.
      // ...
    });
    

    选项 2:更改您的安全规则

    如果您希望所有用户都能够读取您应用中的所有数据,您可以打开如下规则:

    service cloud.firestore {
       match /databases/{database}/documents {
         match /{document=**} {
          allow read: if true;
          allow write: if request.auth != null;
          }
       }
    }
    

    【讨论】:

      【解决方案2】:
      service cloud.firestore {
         match /databases/{database}/documents {
           match /{document=**} {
            allow read;
            allow write: if request.auth != null;
            }
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多