0
0
Firebasecloud~30 mins

Role-based access control pattern in Firebase - Mini Project: Build & Apply

Choose your learning style9 modes available
Role-based access control pattern
📖 Scenario: You are building a simple Firebase app where users have different roles: admin, editor, and viewer. Each role has specific permissions to read or write data in the Firestore database.We want to create a role-based access control (RBAC) pattern using Firebase Security Rules to protect the data.
🎯 Goal: Build Firebase Security Rules that allow:admins to read and write all documents in the posts collection.editors to read all documents and write only their own documents in posts.viewers to only read documents in posts.
📋 What You'll Learn
Create a Firestore collection named posts.
Use Firebase Authentication to identify users and their roles stored in request.auth.token.role.
Write security rules that enforce the RBAC pattern described.
Ensure editors can only write documents where the ownerId field matches their user ID.
💡 Why This Matters
🌍 Real World
Role-based access control is essential in apps to protect data and ensure users only do what they are allowed to do.
💼 Career
Understanding Firebase Security Rules and RBAC is important for cloud developers and security engineers working with Firebase backend.
Progress0 / 4 steps
1
Define the Firestore posts collection structure
Create a Firestore collection named posts where each document has fields title (string), content (string), and ownerId (string). Write the Firestore document example in JSON format assigned to a variable called postExample.
Firebase
Need a hint?

Use a dictionary with keys title, content, and ownerId with string values.

2
Create a variable for user role from authentication token
Create a variable called userRole that extracts the user's role from request.auth.token.role in the Firebase Security Rules syntax.
Firebase
Need a hint?

Assign userRole to request.auth.token.role exactly.

3
Write the core RBAC logic for read and write permissions
Write the main Firebase Security Rules expressions for allow read and allow write on the posts collection. Use userRole to allow:
- admins to read and write all documents,
- editors to read all documents and write only if resource.data.ownerId == request.auth.uid,
- viewers to only read documents.
Use the exact syntax: allow read: if ...; and allow write: if ...;
Firebase
Need a hint?

Use in to check roles for read. For write, check if userRole is admin or editor with ownership.

4
Complete the Firebase Security Rules for the posts collection
Wrap the previous logic inside a match /databases/{database}/documents/posts/{postId} block and a rules_version = '2'; header. Include the service cloud.firestore declaration. Write the full Firebase Security Rules code.
Firebase
Need a hint?

Use a function userRole() inside the match block to return request.auth.token.role. Wrap rules inside service cloud.firestore and match blocks.