Bruno
Bruno

Reputation: 115

Access Firebase Custom Token claims from the Web SDK

If I have a custom token with certain claims and I sign in to Firebase using it, is there any way to access those claims from inside app, using the Web SDK?

For example, if my custom token is like this

{
 :iss => $service_account_email,
 :sub => $service_account_email,
 :aud => "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
 :iat => now_seconds,
 :exp => now_seconds+(60*60), # Maximum expiration time is one hour
 :uid => uid,
 :claims => {:premium_account => is_premium_account}
}

I would like to know if there is something like (from inside the app):

firebase.auth.token.claims.premium_account

I'm not finding anything like this in the docs.

Upvotes: 1

Views: 3406

Answers (3)

Brian M. Hunt
Brian M. Hunt

Reputation: 83818

It looks like you want getIdTokenResult:

await firebase.auth().currentUser.getIdTokenResult()

Upvotes: 5

ecalvo
ecalvo

Reputation: 341

Here is the documentation on it: https://firebase.google.com/docs/auth/admin/custom-claims

I think the gist of it, is once you have custom claims appended to a user via backend code (admin sdk OR firebase functions), you can base64 decode the currentUser token. The documentation references a mozilla article on javascript base64 decoding: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

You can JSON.parse the decoded token and your custom claims will show up there. The documentation is pretty good about it.

Upvotes: 0

crawler
crawler

Reputation: 348

claims is embedded in the token.

Here is an example code to extract the claims from the token using jwt-decode on a web client:

import jwt_decode from './jwt-decode';

firebase.auth().currentUser.getToken().then((token) => {
    console.log(token);
    console.log(jwt_decode(token));
});

Upvotes: 1

Related Questions