0

I have a structure like the following. The subfolders follow the same structure from the root. How do I set Firebase storage rules to only allow admin to add/edit/delete the private subfolder and allow anyone on my app to read the public subfolder?

Root >> folder 1 >> public subfolder
                >> private subfolder
...

     >> folder n >> public subfolder
                >> private subfolder
fractal
  • 1,649
  • 17
  • 31
  • Maybe you would like to edit the question to show the rules you have now that don't work the way you expect, along with the code that accesses them? There are plenty of examples to start with in the documentation. You will need to define and implement for yourself what it means to be "admin". That is not a concept that security rules provide for you natively. https://firebase.google.com/docs/rules/basics – Doug Stevenson Jul 12 '21 at 00:45
  • It depends on what you mean by 'admin.' Are you trying to specify user roles? – Joel Hager Jul 12 '21 at 02:58

1 Answers1

2

Best way would be to use Firebase custom claims. These provides the ability to implement various access control strategies, including role-based access control, in Firebase apps.

You would have to add the "admin" claim to your users. Only the Admin SDK (which must be used in a secure environment like cloud functions or your own server) can add these custom claims. You can refer to this answer for a simple example on adding custom claims. Once you've added the "admin" claim to the relevant users, you can try these security rules:

match /{folderName}/private {
  allow read, write: if request.auth != null && request.auth.token.admin;
}

match /{folderName}/public {
  allow read: if true;
}
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • {folderName} is a standard variable recognised by the firebase rule system? – fractal Jul 13 '21 at 10:17
  • @fractal no that's just a wildcard to match any matching path. You can rename it. – Dharmaraj Jul 13 '21 at 10:17
  • I'm using flutter with firebase auth and when logging in with google provider it sends a payload of data. The registered users are also seperately stored in firestore collection. So there is no simpler way apart from custom claims (and cloud function) to indicate it's a user that exists in this seperate collection to indicate they've registered? I was hoping firebase auth would be a one stop shop (as they would be logging in with firebase auth mechanism on my flutter web/mobile app). I'm using this technique: https://firebase.flutter.dev/docs/auth/usage/ – fractal Jul 13 '21 at 10:21
  • What if instead of "&& request.auth.token.admin;" you put some pseudo logic to check if user exists in a collection with a specific role? Whats the difference between custom claims and a database lookup? – fractal Jul 14 '21 at 22:20
  • @fractal no. That's possible only in Firestore's rules. You cannot read data in Firestore in security rules of Firebase storage. – Dharmaraj Jul 15 '21 at 04:53