Home > OS >  How to grant access to google cloud storage buckets based on users auth uid
How to grant access to google cloud storage buckets based on users auth uid

Time:02-08

I am running a cloud function that saves images like this:

//Pseudocode
const admin = await import("firebase-admin");
const bucket = admin.storage().bucket();
const file = bucket.file('myName');
const stream = file.createWriteStream({ resumable: false });
...

After the images are uploaded, I get the publicUrl like so

file.publicUrl()

and store it in an Object.

This object then gets stored to firestore.

When I now copy this url from the object(the url structure looks like this) https://storage.googleapis.com/new-project.appspot.com/ZWHpYGSQWYXLlUcAwkRFQLC0u7s1/f2a48bdc-7eb3-4174-9f6e-3fd963003bd7/177373254.png

and paste it into a browser field am getting an error:

<Error>
  <Code>AccessDenied</Code>
  <Message>Access denied.</Message>
  <Details>Anonymous caller does not have storage.objects.get access to the Google Cloud Storage 
  object.</Details>
</Error>

even with the test rules:

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read: if true;
      allow write: if false;
    }
  }
}

I have read some issues here on stackoverflow and it seems like this is because I am using google cloud storage buckets and not firebase storage buckets (I thought they are the same)

but I am very confused about how to write rules in this case, so that only authenticated firebase users can read files.

Any help is highly appreciated.

CodePudding user response:

The bucket is shared between Firebase and Cloud Storage, but the way you access the bucket is quite different.

When you access the bucket through a Firebase SDK, or through a download URL generated by a Firebase SDK, your access goes through a Firebase layer. This layer enforces the security rules (for the SDK), and grants temporary read-only access to the download URL.

When you access the bucket through a Cloud SDK, or a signed URL generated by a Cloud SDK, your access does not go through any Firebase layer, and thus Firebase security rules have no effect on this access.

The public URL you have is just a way to identify a file in your Cloud Storage bucket. It does not have any implied access permissions. You will need to make sure the IAM properties for your bucket allow the access you want the user to have to the file.

  •  Tags:  
  • Related