Unable to set custom claims using Firebase Auth's setCustomClaims() method

I am encountering an issue with setting custom claims for Firebase Authentication service's token. I am using a Cloud function to establish the custom claims for Hasura. The cloud function is triggered upon the creation of a new user to set the custom claims. Below is the code running in the 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);
        })
})

On my frontend web page, I am executing the following code to retrieve 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 am unsure as to what mistake I am making, but the token does not include the custom claims that were set in my Cloud function processSignup(). Although I can verify that the function ran without any errors by checking the logs and seeing the entry SUCCESS: Custom claims attached.

If anyone could assist me in resolving this issue, I would greatly appreciate it.

Answer №1

When updating claims, it does not trigger an onAuthStateChanged, meaning the user's authentication state remains the same (logged in or not), but their claims have changed. Tokens are minted and then used for approximately 1 hour.

If you are using getIdTokenResult without forcing a refresh, you can try the following:

let idToken = await user.getIdTokenResult(true);

This will prompt a new token to be fetched from the server, potentially including your custom claims.

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

Every checkbox on the Angular 6 platform has been chosen

In my model class named processAnexOne.ts, I have the following structure: export class ProcessAnexOne { documentList: string; } Within the component class, I have initialized an instance as follows: export class ProcessAnexOneComponent implements O ...

What could be causing the res.sendfile() method to fail when invoked through a jQuery ajax call?

Problem: The first ajax call in the main.js is functioning correctly, but there seems to be an issue with the second one. Although it appears to be working initially, I suspect that there may be a bug present. Upon clicking the button, I am able to access ...

Having trouble with your mobile dropdown menu not responding to clicks?

I'm having trouble getting a dropdown menu to work on the mobile version of my website. When I click on the dropdown menu image, it's supposed to appear, but it's not working as expected. JSFiddle: https://jsfiddle.net/xfvjv184/ Included ...

Avoid the need for users to manually input dates in the Custom Date Picker

After referencing this custom Date picker in ExtJs with only month and year field, I successfully implemented it. However, I am facing an issue where manual entry into the date field is not disabled. My goal is to restrict input for that field solely thr ...

Determine whether a WebElement contains a particular content within the :after pseudo class

After locating my element in Selenium, I've come across an interesting challenge. IWebElement icon = box.FindElement(By.ClassName("box-icon")); Sometimes, this element (icon) has a content set as follows: &:after { content: $icon-specia ...

The page is not able to be uploaded successfully, receiving a HTTP 200 status

Currently, my application is running in Express and I have a button that sends a POST request to the server. After receiving a 200 OK response, the HTML page is displayed. The issue I am facing is that even though I can see the HTML payload in Firebug, my ...

Sort the elements within the *ngFor loop according to the category upon clicking the button in Angular

Currently, I have a collection of items that I am iterating through using *ngFor. Above this list, there are category buttons available as shown in the HTML snippet below. My goal is to enable filtering of the list based on the category of the button click ...

Switching the input type from file to text

My request is to have a file input type that is initially set as read-only, yet still allows the user to manually enter the file name in a text box. Is there a way to achieve this? I want to be able to write the file name similarly to how I would input t ...

Freeze your browser with an Ajax request to a specific URL

There is a function in my view that transfers a value from a text box to a table on the page. This function updates the URL and calls another function called update_verified_phone(). The update_verified_phone() function uses a model called user_info_model( ...

Exploring the depths of JavaScript JSON elements

After processing my PHP code, it generates a JSON output that contains multiple entries in the same structure. Here is an example with two entries: { "0": { "campaign_id": "31", "title": "new title", "description": "new descrip ...

What could be causing the "502 Gateway" error specifically for POST requests in my NextJs app hosted on Firebase?

I've encountered an issue while trying to build an API with the NextJs framework and hosting it on Firebase (Hosting and Functions). The GET requests work fine, but when I try to send a POST request, I keep getting a "502 Bad Gateway" error. To repli ...

Steps to invoke a function in a PHP file from an external JavaScript file

Can anyone assist me with calling the function below in my PHP file? function update_hidden_input(saved_tokens, hidden_input) { var token_values = $.map(saved_tokens, function (el) { //alert(el[settings.tokenValue]); return el[ ...

altering the directory for bower installations on specific repositories exclusively

Recently, I've been experimenting with Bower and at the same time exploring Polymer. If you want to download polymer elements using bower, you can use the following command: bower install --save PolymerElements/iron-image I assume there's a sp ...

The function Jquery .stop does not exist

I am encountering an issue with the magicline.stop function while attempting to implement an underline sliding effect for my navbar. I have tried to troubleshoot the problem but have been unsuccessful so far. Below is the code snippet: <nav class=" ...

Choose to either check or uncheck boxes using ReactJS

After successfully creating a function to select either single or multiple boxes, I encountered an issue with the "Select all" feature. Any suggestions on how to resolve this? (I'm utilizing the material-ui library for my checkboxes, which are essenti ...

Generate table rows by automatically summing the rows and column data using a loop

I'm currently working on a form that dynamically adds data to columns and rows. While I've successfully generated the column names based on database data and used a loop to add details, adding rows has proved to be quite challenging :) Is ther ...

Adjust the button's color even after it has been clicked

My goal is to update the button's color when it's clicked. I found some examples that helped me achieve this, but there's an issue - once I click anywhere outside of the button, the CSS class is removed. These buttons are part of a form, and ...

Oops! Looks like something went wrong. The command to install the debug app failed because the emulator could not be launched. This could be due to the fact that no emulators were found

I'm in need of assistance to resolve these issues Encountered an error while trying to install the app. Please ensure that your Android development environment is properly configured: https://reactnative.dev/docs/environment-setup. Error: Command fai ...

Dynamic Loading of Multiple Scripts on a Webpage with Dependencies in JavaScript

I am currently working on developing a page constructor entirely using JavaScript. The issue arises when I dynamically add two scripts to the page that are dependent on each other. For instance, in this scenario, I am loading jQuery from a CDN, and in the ...

When the horizontal scroll is turned off, it also disables the functionality of my mobile-friendly

I came across a helpful post on StackOverflow that suggested using the following code to disable horizontal scrolling: html, body { overflow-x: hidden; } This solution did resolve my issue of horizontal scrolling, but unfortunately it caused problems ...