Node Script Creating Firebase Custom Claims

0

By Ron Royston

Originally Published 7/2/2019
Updated 7/2/2019

Introduction

This article includes a Node script implementing Firebase Admin SDK custom claims. The use case is documented.

The Firebase Admin SDK supports defining custom attributes on user accounts. This provides the ability to implement various access control strategies, including role-based access control, in Firebase apps. These custom attributes can give users different levels of access (roles), which are enforced in an application's security rules.

Note that security rules must be implemented against the custom attributes to define access based on a users role. For details, see Control Access with Custom Claims and Security Rules. For example, once you have an admin attribute added to a user, a Firestore rule is as easy as

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.token.admin == true;
    }
  }
}

Prerequisites

The user must exist in the Firebase Authentication system and the Firebase Admin SDK must be installed on your machine. The Admin SDK uses a service account to authenticate to your Firebase project. For instructions see Add the Firebase Admin SDK to Your Server. Node.js can be downloaded here.

The Node Script

The script below expects the users uid as the only argument. The uid is the identifier assigned by the Firebase Authentication system and can be found in the Firebase console. To run the script, node admin-add <users-uid-here>.

var admin = require('firebase-admin');
var serviceAccount = require("./<your-service-account-specific-string-here>.json");
var uid = process.argv[2];

if(uid){
    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
        databaseURL: "https://<your-project-id-here>.firebaseio.com"
    });
    return admin.auth().setCustomUserClaims(uid, {admin: true}).then(() => {
        console.log("Custom Claim Added to UID.");
        process.exit();
    }).catch(function(error) {
        console.log('Error adding admin:', error);
        process.exit();
    });
} else {
    return console.log("uid argument required");
    process.exit();
}

Automate a workflow or process today with standards based, library free JavaScript in the browser, in the cloud with NodeJS, or both. High Tekk can do that! See our services page for more details.

Dialog Title

Cell Phone Number

Your order ID is . The grand total is , or bitcoin.

This action cannot be undone. Continue?

Changes will be lost. Continue?

Delete location?






A signin link will be sent to your email address.

You privacy is top priority. Email addresses are never shared with a third party. For more information see our privacy policy.

Find a bug? Experience an error? How can we do better? We appreciate your feedback.

Delete order? This action cannot be undone.

Delete order? This action cannot be undone.