Is There Any Function In User Authentication For User Roles?
Solution 1:
There is no "user roles" API for Firebase Auth, but there are ways that you can implement role based authorization in your application.
Database
One of the ways is, as you mentioned, to store that data in your database. The benefits of doing that is that it's easy to implement.
You can enforce the rules by making lookups in your database rules for both Firestore and the Realtime database.
Realtime database
{
"rules": {
"adminContent": {
".write": "root.child('users').child(auth.uid).child('admin').val() === true"
}
}
}
Firestore
service cloud.firestore {
match /databases/{database}/documents {
match /articles/{article} {
allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true
}
}
}
The downside of maintaining your roles and and credentials in database is that you can't use that information across products. You can't write a firestore database rule that access the RTDB rules or vice versa.
Custom claims
If you want your roles to work across services (using the same role data in RTDB, Firestore and Firebase Storage), then you should look into setting custom claims, which is explained very well in the documentation.
Once that is set up you can use the custom claims to implement role based or group access rights across the different products.
database.rules.json
{
"rules": {
"adminContent": {
".read": "auth.token.admin === true",
".write": "auth.token.admin === true",
}
}
}
firestore.rules / storage.rules
The Firestore and Storage rules has similar syntax for the rules and you fill find that the allow
statement is the same for both.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.token.admin == true;
}
}
}
Post a Comment for "Is There Any Function In User Authentication For User Roles?"