2
votes

I am facing a problem with setting custom claims for Firebase Authentication service's token. I am using Cloud function to set the custom claims for Hasura. The cloud function executes upon new user create event to set the custom claims. Here's my code running in cloud function

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

exports.processSignup = functions.auth.user().onCreate(user => {
    // create custom claims for hasura
    const hasuraClaims = {
        "x-hasura-default-role": "user",
        "x-hasura-allowed-roles": ["user"],
        "x-hasura-user-id": user.uid
    }

    // attach claims to user auth object
    return admin.auth().setCustomUserClaims(user.uid, hasuraClaims)
        .then(_ => {
            functions.logger.info('SUCCESS: Custom claims attached');
        })
        .catch(err => {
            console.log('ERROR: ', err);
        })
})

In my frontend web page, I am running the following code to get the idToken

// subscribe to user state change
firebase.auth().onAuthStateChanged(async user => {
    console.log('Firebase auth state changed');

    if (user) {
        // User is signed in.
        window.User = user;

        let idToken = await user.getIdTokenResult();
        console.log('idToken: ', idToken);
    }
})

I don't know what I'm doing wrong, but the token doesn't contain the custom claims that I've set in my Cloud function processSignup(). I know that the function executed without error because I can check my function logs and find the info entry SUCCESS: Custom claims attached.

Can anyone please help me solve this problem?

1

1 Answers

2
votes

Updating claims does not trigger an onAuthStateChanged (the auth state of being logged in or not has not changed, but the users' claims have) and tokens are minted and then used for ~1h.

You are calling getIdTokenResult but not forcing a refresh, try:

let idToken = await user.getIdTokenResult(true);

which will force a new token to be fetched from the server and will (hopefully) include your custom claims.