Skip to content

Instantly share code, notes, and snippets.

@k2wanko
Created September 17, 2023 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k2wanko/289f5cf231ca80da099c7414dceb465d to your computer and use it in GitHub Desktop.
Save k2wanko/289f5cf231ca80da099c7414dceb465d to your computer and use it in GitHub Desktop.
How to use External Account of Workload Identity with Firebase Admin SDK
// I have confirmed to the point of using Firestore from AWS Lambda (node v18).
import admin from 'firebase-admin'; // version 11.10.1
import { Credential } from 'firebase-admin/app';
import { ComputeEngineCredential } from '../node_modules/firebase-admin/lib/app/credential-internal.js';
import { ExternalAccountClient } from 'google-auth-library'; // version 9.0.0
import fs from 'fs/promises';
export class ExternalAccountCredential
extends ComputeEngineCredential // Inherits this class because it is verified to be an internal class at Firestore initialization.
implements Credential
{
async getAccessToken(): Promise<admin.GoogleOAuthAccessToken> {
const json = JSON.parse(
await fs.readFile(
process.env.GOOGLE_APPLICATION_CREDENTIALS as string,
'utf-8',
),
);
const client = ExternalAccountClient.fromJSON(json);
if (!client) {
throw new Error('client is empty');
}
const res = await client.getAccessToken();
return {
access_token: res.res?.data?.accessToken || '',
expires_in: new Date(res.res?.data?.expireTime ?? 1000).getTime() / 1000,
};
}
}
const credential = new ExternalAccountCredential();
const app = admin.initializeApp({
credential,
});
const db = app.firestore();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment