简体   繁体   English

Firebase/Angular:从 Firebase 存储读取 JSON 文件

[英]Firebase/Angular : read JSON file from Firebase Storage

I'm writing an Angular 10 application connected with a standard Firebase setup (Auth/Firestore), and so far so good.我正在编写一个与标准 Firebase 设置(Auth/Firestore)连接的 Angular 10 应用程序,到目前为止一切都很好。

I got an external application that will upload a JSON file to the storage bucket, and I'd like to be able to read it directly from my Angular app.我有一个外部应用程序,它将 JSON 文件上传到存储桶,我希望能够直接从我的 Angular 应用程序中读取它。

The problem is when I do the HTTP GET request, I got a 403 response.问题是当我执行 HTTP GET 请求时,我得到了 403 响应。

====== Here my code ====== ======这是我的代码======

my.service.ts:我的.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 storage rules 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;
    }
  }
}

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

Anyone succeed to read a JSON file direclty WITH authorisation setup?任何人都可以通过授权设置直接读取 JSON 文件吗?

arrrgghhhh.啊啊啊。

After severals hours of testing, reading docs and loosing hairs, I finally understood the issue.经过几个小时的测试、阅读文档和脱发,我终于明白了这个问题。

In the url of JSON file, the token part is dedicated to the "version" of the file in Firebase Storage and nothing related to user token.在 JSON 文件的 url 中,令牌部分专用于 Firebase 存储中文件的“版本”,与用户令牌无关。

The solution is:解决方案是:

  1. to fetch first the token of the file by using fireStorageservice使用 fireStorageservice 首先获取文件的令牌
  2. getting the downloadUrl获取下载地址
  3. and after that do the normal HTTP get request.然后执行正常的 HTTP 获取请求。

Here code sample of the chain calls in my service:这里是我的服务中链调用的代码示例:

  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;
              })
            )
        })
      );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM