Back to results for “Security”
Flutter › Firebase Authentication in Flutter

How can custom claims in Firebase Authentication be used to implement role based access control, such as distinguishing between a regular user and an administrator within your app?

Advanced

Answer

Custom claims let you attach additional custom key value data directly to a user's authentication token, such as marking a specific account with an isAdmin flag set to true, and this custom claim data is set through a trusted, secure backend environment, such as a Cloud Function, rather than ever being set directly from the client side app itself, since allowing a client to freely set its own claims would obviously and completely defeat the entire purpose of using it as a genuinely trustworthy security mechanism, and both your Flutter app and your Firestore security rules can then reliably check for this specific custom claim to correctly determine exactly what a given specific user is actually allowed to do.
// Cloud Function setting a custom claim, never done directly from the client
await admin.auth().setCustomUserClaims(uid, { isAdmin: true });
Real-world example An internal company tool grants specific employees administrative access by setting a secure isAdmin custom claim through a trusted Cloud Function, then checking for that same specific claim both within the Flutter app's own interface logic and within their Firestore security rules to correctly restrict sensitive administrative actions.

Common follow-ups: Why must custom claims always be set from a trusted backend environment rather than directly from the client?;How long does it typically take for a newly set custom claim to actually become reflected within a user's current authentication token?