Custom claims fetched from Admin SDK are returning empty values

I am currently utilizing Firebase cloud functions in conjunction with Android to create a user with custom claims. However, I have encountered an issue where the custom claims are showing up as null despite following the documentation.

Thank you in advance for any help

Here is the code snippet:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

const serviceAccount = require('../serviceAccountKey.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

exports.createSellerAccount = functions.https.onCall((data, context) => {
    const userEmail = data.email;
    const userPassword = data.password;

    return admin.auth().createUser({
        email: userEmail,
        password: userPassword
    }).then((userRecord) => {
        // See the UserRecord reference doc for the contents of userRecord.
        const additionalClaims = {
            premiumAccount: true
        };

        admin.auth().createCustomToken(userRecord.uid, additionalClaims)
            .then(function (customToken) {
                // Send token back to client
            })
            .catch(function (error) {
                console.log("Error creating custom token:", error);
            });

        return {
            sellerAccount: userRecord
        }
    }).catch((error) => {
        // console.log("Error creating new user:", error);
        if (error.code === "auth/email-already-exists") {
            throw new functions.https.HttpsError('already-exists', error.message);
        } else if (error.code === 'auth/invalid-email') {
            throw new functions.https.HttpsError('invalid-argument', error.message);
        } else {
            throw new functions.https.HttpsError('unknown', error.message);
        }
    });

})

Answer №1

Your approach involves generating a customized token rather than updating the existing token with additional claims. For the latter, refer to Set and validate custom user claims via the Admin SDK. This example illustrates how you can achieve this:

// Grant admin privileges to the user identified by uid.

admin.auth().setCustomUserClaims(uid, {admin: true}).then(() => {
  // The newly assigned custom claims will be included in the user's ID token once it is issued.
});

To implement this, obtain the UID of the new user and use the setCustomUserClaims method with it. Subsequently, confirm that the claims have been updated either by waiting for propagation or by inspecting the token within the Node.js script.

I suggest troubleshooting your issue systematically moving forward. Rather than displaying the token in your Android code, consider logging it within your Cloud Functions code. Alternatively, you may want to eliminate the Cloud Functions aspect entirely and test the behavior using a local Node.js environment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connecting data with Angular

Recently, as part of my learning journey with Angular, I encountered an intriguing issue. While working on my code, I noticed that the error popped up in my code editor (VSCode) but not when running the code in the browser. The dilemma stemmed from settin ...

Discover the simple steps to include row numbers or serial numbers in an angular2 datagrid

Currently, I am utilizing angular2 -datatable. Unfortunately, I am facing an issue where the correct row numbers are not being displayed in their corresponding rows. Whenever a user moves to the next page using the paginator, the datatable starts countin ...

Understanding and parsing JSON with object pointers

Is it possible to deserialize a JSON in typescript that contains references to objects already existing within it? For instance, consider a scenario where there is a grandparent "Papa" connected to two parents "Dad" and "Mom", who have two children togeth ...

Improving observables in Angular after triggering a resolver

After successfully creating a Resolver in my code, I am wondering if there is a way to refactor my TypeScript component. Currently, whenever I try to remove any unnecessary parts of the code, it breaks my app. Here is the code for my resolver: @Injectable( ...

Converting JSONSchema into TypeScript: Creating a structure with key-value pairs of strings

I am working with json-schema-to-typescript and looking to define an array of strings. Currently, my code looks like this: "type": "object", "description": "...", "additionalProperties": true, "items": { "type": "string" ...

Recording the details of an Angular project through the utilization of Compodoc

I am currently in the process of documenting my Angular + Typescript application using Compodoc. To install Compodoc, I utilized npm and executed the following command: 'npm install -g compodoc'. And included "compodoc": "./node_modules/ ...

Using TypeScript, leverage bracket notation to access a property of an object using a variable

I am working with an object that has an interface and I am interested in accessing values dynamically using property keys. const userData: IUser = { username: "test", namespace: "test", password: "test" } Object.keys(userData).forEach(propert ...

Popup appears on incorrect page

As part of my app development project, I implemented a popover feature that opens when clicking on a label. Initially, this functioned smoothly within a tab navigation setup. However, after transitioning from tab modules to the app-routing module to displa ...

Clickable Angular Material card

I am looking to make a mat-card component clickable by adding a routerlink. Here is my current component structure: <mat-card class="card" > <mat-card-content> <mat-card-title> {{title}}</mat-card-title> &l ...

Is it possible to define a new type in TypeScript using "runtime" keys?

Illustrate with an example: class ModuleOptions { key1?: string; key2?: string; keyA?: string; keyB?: string; } class Module { static options: ModuleOptions = { key1: 'key1', key2: 'key2', keyA: 'keyA&apos ...

Having trouble using the RxJS filter to sort through records effectively

Despite using the rxjs filter in my angular project, I'm encountering difficulties in filtering records. Here is the function in question: public getOrders(type: string, filterObj = {}, otherParams = {}): Observable<{ name: string; qt: number }[]&g ...

Lack of MaterialUI Table props causing issues in Storybook

Currently, I am utilizing MaterialUI with some modifications to create a personalized library. My tool of choice for documentation is Storybook, using Typescript. An issue I have encountered is that the storybook table props are not consistently auto-gene ...

Can a TypeScript interface inherit from multiple other interfaces simultaneously?

Hello Angular Community, I have a question regarding nesting three interfaces within another interface. Let me explain with some code: I am attempting to integrate the IProject1, IProject2, and IProject3 interfaces into the IAdmin2 interface: Thank you ...

Creating a Prisma schema with a complex nested structure and incorporating an array of strings for a specific property

I'm trying to create a detailed Prisma schema for a product database that includes nested properties and an array of strings for image content. The structure I'm aiming for looks like this: interface Product { id: number; name: string; ...

Ways to universally establish values of a mapped type

Take a look at the code snippet below: type Properties = { item0: { item0: string }; item1: { item1: string }; item2: { item2: string }; item3: { item3: string }; item4: { item4: string }; }; type Func<N extends keyof Properties> = ({}: Pr ...

Encountering an undefined value in Angular outside of the subscription

I am facing an issue where I need to use the value from the user outside the subscribe function in order to assign it to my tweet class. However, when I try to print it outside the subscribe function, it shows as undefined. Can anyone provide a solution fo ...

What is preventing you from utilizing TypeScript's abstract classes for generating React factories, especially when regular classes seem to function properly?

Here is an example showcasing the behavior of TypeScript code using React with abstract classes: import * as React from "react"; class MyComponent<P> extends React.Component<P, any> { static getFactory() { return React.createFacto ...

What is the best way to transform a standard array into a record without losing the specific data types in each position?

Imagine type Individual = { name: string; age: number; }; const john = { name: "John", age: 28, } as const; const emily = { name: "Emily", age: 35, } as const; I am looking to create a function that takes an individual an ...

Renew subscription following interruption

I need to trigger the updatePosition function when the mouseMove event occurs on the document, but not when it is emitted from the testEl.current element: const cursor$ = fromEvent<MouseEvent>(document, 'cursor') const scroll$ = fromEvent(d ...

Troub3leshooting Circular Dependency with Typescript, CommonJS & Browserify

I am currently in the process of transitioning a rather substantial TypeScript project from internal modules to external modules. The main reason behind this move is to establish a single core bundle that has the capability to load additional bundles if an ...