How to Use Custom Claims in Firebase Security Rules
Use
request.auth.token in Firebase security rules to check custom claims set on a user. Custom claims are added via Firebase Admin SDK and can be accessed in rules as request.auth.token.claimName to control access based on roles or permissions.Syntax
Firebase security rules access custom claims through request.auth.token. You check a claim by its name, for example request.auth.token.admin. This returns the value of the custom claim for the authenticated user.
Example parts:
request.auth.token: The object holding all custom claims.claimName: The key of the custom claim you set, likeadminorrole.- Boolean or value check: Use
==orinto verify claim values.
firebase
allow read: if request.auth != null && request.auth.token.admin == true;
Example
This example shows a Firebase security rule that allows reading data only if the user has a custom claim admin set to true. The claim must be set using Firebase Admin SDK before this rule works.
firebase
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /adminData/{docId} { allow read: if request.auth != null && request.auth.token.admin == true; allow write: if false; } } }
Output
Users with the custom claim 'admin' set to true can read documents in 'adminData'. Others cannot.
Common Pitfalls
Common mistakes when using custom claims in Firebase rules include:
- Not setting custom claims correctly via Firebase Admin SDK before expecting them in rules.
- Forgetting to refresh the user's ID token after setting claims, so the client does not have updated claims.
- Checking
request.auth.tokenwithout verifyingrequest.auth != null, which causes errors for unauthenticated users. - Using incorrect claim names or types (e.g., string vs boolean).
firebase
/* Wrong: Missing auth check */ allow read: if request.auth.token.admin == true; /* Right: Check auth first */ allow read: if request.auth != null && request.auth.token.admin == true;
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Custom Claims Access | Use request.auth.token.claimName to read claims | request.auth.token.admin == true |
| Auth Check | Always verify user is authenticated first | request.auth != null |
| Claim Types | Claims can be boolean, string, or number | request.auth.token.role == 'editor' |
| Token Refresh | User must refresh ID token after claim update | firebase.auth().currentUser.getIdToken(true) |
| Setting Claims | Use Firebase Admin SDK to set claims | admin.auth().setCustomUserClaims(uid, {admin: true}) |
Key Takeaways
Always check if the user is authenticated before accessing custom claims in rules.
Access custom claims in rules via request.auth.token.claimName.
Set custom claims using Firebase Admin SDK and refresh user tokens to apply changes.
Use custom claims to control access based on roles or permissions securely.
Test rules carefully to avoid unauthorized access or blocking valid users.