Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access custom claims?

I am trying to access custom claims I set for my users according to this documentation article.

I cannot find a customClaims member in the FirebaseUser class of the Firebase Authentication Flutter plugin.

How do I access Firebase Authentication custom claims in Flutter?

Note: I have the following custom claims:

"customClaims": {
  "admin": true
}
like image 573
creativecreatorormaybenot Avatar asked Nov 28 '25 00:11

creativecreatorormaybenot


1 Answers

You can get access to the user's claims using FirebaseUser.getIdTokenResult.
The IdTokenResult returned from the Future that is returned by the method contains useful information about the authentication token, such as the time of authentication, the expiration time of the token, the signin provider, etc., but it also contains the user's claims and with that also your custom claims.

Future<Map<dynamic, dynamic>> get currentUserClaims async {
  final user = FirebaseAuth.instance.currentUser;

  // If refresh is set to true, a refresh of the id token is forced.
  final idTokenResult = await user.getIdTokenResult(true);
  
  return idTokenResult.claims;
}

If you call the getter now (await currentUserClaims), it will return a Map<dynamic, dynamic> with all of the user's claims, not just the custom claims. This will look something like this (in this case the user used the phone signin provider):

{
  phone_number: <phone number>,
  firebase: {
    identities: {
      phone: [<phone number>]
    }, 
    sign_in_provider: phone
  }, 
  user_id: <user id>, 
  aud: <project id>, 
  exp: <expiration time in milliseconds since epoch>, 
  iat: <issued at time in milliseconds since epoch>, 
  iss: https://securetoken.google.com/<project id>, 
  sub: <user id>, 
  auth_time: <authentication time in milliseconds since epoch>, 
  admin: true, # This is your custom claim!
}

You can see the custom claim at the end. This means that you can check it like this:

final isAdmin = (await currentUserClaims)['admin'] == true;
like image 178
creativecreatorormaybenot Avatar answered Dec 01 '25 05:12

creativecreatorormaybenot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!