Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Custom Claims without Cloud Functions

Is there a way to create a custom claim without having to go through cloud functions?

I really only need to set it up for a few accounts, and my current plan is spark. I can't upgrade just yet. But I need to test this feature to implement role based authentication.

Thank you and please be as detailed as possible as I'm new to firebase cli.

like image 550
user135019 Avatar asked Sep 20 '25 05:09

user135019


1 Answers

Yes, if you just need to setup a few users then you run a script locally to add the claims. Just follow the steps:

1. Create a NodeJS project

npm init -y

//Add Firebase Admin
npm install firebase-admin

2. Write this code in a JS file (addClaims.js):

const admin = require("firebase-admin")

admin.initializeApp({
  credential: admin.credential.cert("./serviceAccountKey.json"),
  databaseURL: "https://<project-id>.firebaseio.com/"
})

const uid = "user_uid"

return admin
  .auth()
  .setCustomUserClaims(uid, { admin: true })
  .then(() => {
    // The new custom claims will propagate to the user's ID token the
    // next time a new one is issued.
    console.log(`Admin claim added to ${uid}`)
  });

3. Run the script

node addClaims.js

You can also write a function that takes an array of UIDs as parameter and adds claims to all of them using a loop. To read more about service account and initializing the Admin SDK, check this documentation.

like image 66
Dharmaraj Avatar answered Sep 22 '25 07:09

Dharmaraj