Storage Rules for Firebase (Visual Tutorial)

What if I told you that Every year, companies lose $400,000 million to hackers?

Because the next generation of computers will be more cheaper, quicker, and better, the figure might reach 600 billion dollars by 2021.

Isn't it an intimidating figure?

Storage Rules Firebase

Most mobile app developers are unconcerned until their apps are hacked.

Isn't it wiser to make good use of Firebase Storage Rules? Yes, of course.

What's the best part?

You don't have to worry about managing infrastructure or writing complex server-side authentication and authorization code, so you can focus on providing a fantastic user experience.

Understand the Basics of Firebase Security

Do you have any idea?

You must first grasp how something works before you can hack it.

Furthermore, Firebase AUTH assists your user in logging into your app.

Additionally, Firebase storage security rules make it easy to approve (authorize) users and validate their requests.

[the_ad id=”4951″]

A few lines of code are all that is required to prevent or provide access to specified users to particular material.

Similarly, practically any security tool requires you to understand the fundamental component of security.

Here we go:

1. Authentication

Authentication is an important aspect of the application development process.

For user side authentication, Firebase provides an easy-to-use, secure authentication mechanism.

You must enable Firebase authentication in your app if you wish to configure user-based security policies.

Authentication is an essential part of the app development process.

Firebase provides an easy-to-use, secure authentication mechanism on the user side.

If you want to set up user-based security policies, you'll need to activate Firebase authentication in your app.

2. Authorization

Authorization is critical for security since it allows you to identify who your users are.

If you know who your users are, you can give them certain guidelines to follow.

You can, for example, designate a small number of users who are capable of writing material or reading an image, and so on.

Furthermore, in order to conduct any task, the default Security Rules of Cloud Storage need the use of the Firebase Authentication service. All files can be written to, read from, or have operations performed on them.

You may also alter the rules in the Storage navigation rules sections of the Firebase Console.

3. Data Validation

Cloud Storage security rules can also be handled during data validation.

It means you may check the file's path, name, and metadata properties like content-type and size, among other things.

service firebase.storage 
{
  match /b/{bucket}/o 
  {
    match /images/{imageId} 
{
      // Only enable uploads of any image file that is but 5MB
      allow write: if request.resource.size < 5 * 1024 * 1024
                   && request.resource.contentType.matches('image/.*');
    }
  }
}

Let's get into the practical side of security rules now that we've covered the basics.

In the Firebase Console, Create Storage Security Rules:

Step 1 - To begin, go to the Firebase Console and choose your current project.

Step 2 - What if you don't have a project? Please make a new one.

Step 3 - Now you may see your default security rules and go to the next step.

Step 4 - After that, select the location of the cloud storage server and click Finish.

Step 5 - It will take a few moments for your project to fully load.

Step 6 - After that, you'll see your Dashboard.

You can edit and publish your security rules here, but it's always a good idea to test them in the simulator first.

You can get a better grasp of how the simulator works by watching the video included at the conclusion of this guide.

You may also keep track of your rules and how they're being used.

Learn How to Secure Files:

Storage Security Rules also makes it simple and quick to safeguard your or your users' files.

1. Understanding of Rules

You can assign users who can or cannot access files saved on Cloud Storage using Firebase Storage Security Rules.

Aside from that, there's the question of how the files are handled and what kind of metadata they contain.

The most fundamental rule is the allow rule, which allows write and read requests provided a condition is met.

//The rule evaluates to true if no condition is specified.
allow read;

//A condition can be specified as an option in rules.
allow write: if <condition>;

//Multiple request methods can also be specified in rules.
allow read, write: if <condition>;

2. Matching Paths

File paths used to obtain files in Storage are matched by Cloud Storage Rules. Storage Security Rules can be nested and can match wildcard pathways or exact same paths. If no matching rule enables a request method, or if the requisite condition is false, the request will be refused.

2.1) Exact Matches

In this case, match is the keyword, /images is the folder name, and profilephoto.png is the exact image stored on Firebase Storage. You can immediately place a rule in this manner.

// "images/profilePhoto.png" is an exact match.
match /images/profilePhoto.png {
  allow write: if <condition>;
}

// "images/croppedProfilePhoto.png" is an exact match.
match /images/croppedProfilePhoto.png {
  allow write: if <other_condition>;
}

2.2) Nested Matches

You can also use layered rules to organise your rules. Match/images, for example, will choose everything in the images folder. After that, you can choose the rest of the items.

//For files that begin with the word "images," there is a partial match.
match /images {
  //"images/profilePhoto.png" is an exact match.
  match /profilePhoto.png {
    allow write: if <condition>;
  }

  //"images/croppedProfilePhoto.png" is an exact match.
  match /croppedProfilePhoto.png {
    allow write: if <other_condition>;
  }
}

2.3) Wildcard Matches

With the use of wildcards, security rules can be applied to a pattern. The wildcard is simply a named variable that can be used to define either a single string, such as profilePicture.png, or several path segments, such as images/profilePicture.png. You can make a wildcard by putting curly(Middle) brackets around it and putting a wildcard name within it, such as stringdemo. You can also make a multi-segment wildcard by appending =** to the wildcard name, such as path=**.

//For files that begin with the word "images," there is a partial match.
match /images {
  // "images/*" is an exact match.
  // e.g. images/profilePhoto.png is matched
  match /{imageId} {
    // Only one path segment (*) is matched by this rule.
    // imageId is a string that holds the matched segment's unique identifier.
    allow read: if <condition>;
  }

  // "images/**" is an exact match.
  // e.g. images/users/user:12345/profilePhoto.png is matched
  // images/profilePhoto.png is also matched!
  match /{allImages=**} {
    // One or more path segments (**) are matched by this rule.
    // allImages could be a path that contains all segments matched
    allow read: if <other_condition>;
  }
}

3. Request Evaluation

What is delivered to Firebase storage is used to determine downloads, uploads, deletions, and metadata changes. Each request (variable) contains the path to the file where the request is being made, as well as the precise time when the request is received. The state of HTTP authentication and headers is also inserted.

4. Resource Evaluation

Perhaps you want to judge the metadata of a particular file that is being downloaded, uploaded, deleted, or modified while making rules. This allows you to create elaborate and robust rules that do things like only allow files with specified content types to be uploaded or only delete files larger than a certain size.

User-Based Security

The Firebase cloud storage security rules work in tandem with the Firebase authentication service. The user will have a richer experience as a result of this.

The User's Authentication

When a verified (authenticated) user makes a request on Firebase Storage, the request.auth (variable) appears with the user's Id (request.auth.uid), and it uses request.auth.token to keep track of the Firebase auth JWT (JSON Web Token).

Public

A security rule that prevents requests from being accepted. Because it does not recognise a user's auth context, auth context becomes a public rule. These security rules can be used to surface public data such as gaming assets, sound, or other static material, among other things.

// If the file size is less than 100kB, anyone can read it.
// Anyone with a public file ending in '.txt' can upload it.
match /public/{imageId} 
{
  allow read: if resource.size < 100 * 1024;
  allow write: if imageId.matches(".*\\.txt");
}

Private Authentication

In some circumstances, you may wish to display data to all users who have authenticated with your app while hiding it from unauthenticated users. Every unauthenticated user is represented by the request.auth (variable).

// All internal image reads should require authentication.
match /internal/{imageId} 
{
  allow read: if request.auth != null;
}

User Private

In most circumstances, request.auth is used in this way. It will provide individual users with appropriate file rights, such as the ability to post profile images and access confidential papers.

//Anyone can see a user's profile image, but only that user can upload it.
match /users/{userId}/profilePicture.png {
  allow read;
  allow write: if request.auth.uid == userId;
}

Private Group

Allowing group access on a specific object, such as allowing multiple members of the team to collaborate on a shared document, is another relatively straightforward use case. There are numerous options for doing so.

// Allow reads if the group ID in your token matches the owner property in the file metadata.
// Allow writes if the user's custom token has the group ID.
match /files/{groupId}/{fileName} {
  allow read: if resource.metadata.owner == request.auth.token.groupId;
  allow write: if request.auth.token.groupId == groupId;
}

Post a Comment

Previous Post Next Post