Firebase Custom Claims with Admin SDK on Node.js

Ronnie Royston
2 min readJan 4, 2023

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();
}

--

--

Ronnie Royston

Delivering refined solutions via vigorous practice. Tulane ('97), Cisco CCIE# 6824, Google Certified Professional Cloud Architect, and USPA Master Skydiver