Created
September 17, 2023 21:37
-
-
Save k2wanko/289f5cf231ca80da099c7414dceb465d to your computer and use it in GitHub Desktop.
How to use External Account of Workload Identity with Firebase Admin SDK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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