This tutorial aims to provide an understanding of how to create Firebase Security Rules for anonymous users. By the end of the tutorial, you will be able to set up security rules that allow access to specific resources in your application for users not logged in.
Firebase Security Rules stand as the guard between Firebase services like Cloud Firestore, Firebase Storage, and the users of your app. They use expressions to determine whether to allow or deny requests to read and write data.
In Firebase, anonymous users are treated as authenticated users with a unique user ID. Therefore, we can use the request.auth.uid
property in our rules to identify anonymous users and restrict or allow access to our data accordingly.
service cloud.firestore {
match /databases/{database}/documents {
// Match any document in the 'public' collection
match /public/{document=**} {
allow read: if request.auth != null;
}
}
}
In this example, we're allowing any authenticated user (including anonymous users) to read data from the 'public' collection. The request.auth != null
condition checks if a user is authenticated.
service cloud.firestore {
match /databases/{database}/documents {
match /private/{document=**} {
allow write: if request.auth != null && request.auth.token.firebase.sign_in_provider != 'anonymous';
}
}
}
Here, we are allowing write access to the 'private' collection only to non-anonymous users. The request.auth.token.firebase.sign_in_provider != 'anonymous'
condition checks if the user is not anonymous.
In this tutorial, we've learned about Firebase Security Rules and how to write rules for anonymous users. We've covered how to allow anonymous users to read data, and how to restrict write access to non-anonymous users.
For further learning, you can explore more complex rules and conditions, as well as how to debug and test Firebase Security Rules.
service cloud.firestore {
match /databases/{database}/documents {
match /any/{document=**} {
allow read;
allow write: if request.auth != null && request.auth.token.firebase.sign_in_provider == 'anonymous';
}
}
}
This rule allows read access to all users but restricts write access to anonymous users only.
service cloud.firestore {
match /databases/{database}/documents {
match /exclusive/{document=**} {
allow read, write: if request.auth != null && request.auth.token.firebase.sign_in_provider != 'anonymous';
}
}
}
This rule restricts both read and write access to non-anonymous users only.