Ad

Cloud Functions - User Custom Claims Returns Undefined

I created a new user using custom token with additional claims.

I can able to access the claims in Firestore security rules but in cloud functions it returns undefined.

Code for creating user:

admin.auth()
.createCustomToken(uid, claims)
.then(token => {
    console.log(token);
 });

Code for getting created user:

admin.auth().getUser(uid)
.then((userRecord) => { 

 console.log(userRecord.customClaims);

});

userRecord.customClaims returns undefined

Ad

Answer

You should use setCustomUserClaims(). Not createCustomToken().

admin.auth()
.setCustomUserClaims(uid, claims)
.then(token => {
    console.log(token);
 });

setCustomUserClaims() is always override, so I recommend to get current customClaims and merge.

It depends on the situation, I recommend to use async/await.

Like this.

async function setClaims(uid, claims) {
    try {
        const userRecord = await admin.auth().getUser(uid);
        return await admin.auth().setCustomUserClaims(uid, {
            ...userRecord.customClaims,
            ...claims
        });
    } catch (e) {
        return Promise.reject(e);
    }
}

See

Updated

setCustomUserClaims()

Sets additional developer claims on an existing user identified by the provided uid

See

createCustomToken()

Creates a new Firebase custom token (JWT) that can be sent back to a client device to use to sign in with the client SDKs' signInWithCustomToken() methods.

You can also optionally specify additional claims to be included in the custom token. For example, below, a premiumAccount field has been added to the custom token, which will be available in the auth / request.auth objects in your Security Rules:

It's only available in the auth / request.auth objects in your Security Rules. So not set user customClaims.

See

Ad
source: stackoverflow.com
Ad