首页 > 解决方案 > Firebase/Angular:从 Firebase 存储读取 JSON 文件

问题描述

我正在编写一个与标准 Firebase 设置(Auth/Firestore)连接的 Angular 10 应用程序,到目前为止一切都很好。

我有一个外部应用程序,它将一个 JSON 文件上传到存储桶,我希望能够直接从我的 Angular 应用程序中读取它。

问题是当我执行 HTTP GET 请求时,我得到了 403 响应。

======这是我的代码======

我的.service.ts:

    const url = 'https://firebasestorage.googleapis.com/v0/b/my-project/o/test%2Fbehaviors.json?alt=media&auth='+this.ss.getCurrentToken();

 const headers = new Headers({
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${this.ss.getCurrentToken()}`
    });

const collection2 = this.http.get(url, { headers: headers })
      .pipe(
        map(behaviors => {
          console.log(behaviors)
        })
      );

Firebase 存储规则

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if false;
    }
       
    match /test/{allPaths=**} {
      allow read: if request.auth != null; // note if I set TRUE directly it s working but without auth
      allow write: if false;
    }
  }
}

==================

任何人都可以通过授权设置直接读取 JSON 文件吗?

标签: javascriptangularfirebase-storage

解决方案


啊啊啊。

经过几个小时的测试、阅读文档和脱发,我终于明白了这个问题。

在 JSON 文件的 url 中,令牌部分专用于 Firebase 存储中文件的“版本”,与用户令牌无关。

解决方案是:

  1. 使用 fireStorageservice 首先获取文件的令牌
  2. 获取下载地址
  3. 然后执行正常的 HTTP 获取请求。

这里是我的服务中链调用的代码示例:

  const this.fs.ref('test/behaviors.json').getDownloadURL()
      .pipe(
        switchMap((url) => {
          return this.http.get(url)
            .pipe(
              map(behaviors => {
                console.log(behaviors)
                const pList = [];
                Object.keys(behaviors).forEach(doc => {
                  pList[behaviors[doc].key] = behaviors[doc];
                });
                return pList;
              })
            )
        })
      );

推荐阅读