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.

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.

The problem is when I do the HTTP GET request , I got a 403 response.

====== Here my code ======

my.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

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 ?

31 thoughts on “Firebase/Angular : read JSON file from Firebase Storage”

  1. 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.

    The solution is:

    1. to fetch first the token of the file by using fireStorageservice
    2. getting the downloadUrl
    3. and after that do the normal HTTP get request.

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

Leave a Comment