如果您使用 firebase-tools 作为模块,您可以通过以下方式获取用户的刷新令牌
import { getGlobalDefaultAccount } from "firebase-tools/lib/auth.js";
const account = getGlobalDefaultAccount();
console.log(account.tokens.refresh_token);
我正在寻找一种方法来使用登录用户的(firebase-tools)刷新令牌作为 Firebase Admin SDK 的凭据。比如:
import { initializeApp, refreshToken } from "firebase-admin/app";
const admin = initializeApp({
credential: refreshToken(account.tokens.refresh_token),
});
我尝试运行上面的代码片段,但看起来
refreshToken
方法将 account.tokens.refresh_token
解释为文件路径(可能因为它是一个字符串)。所以我尝试将其更改为这样的对象:
import { initializeApp, refreshToken } from "firebase-admin/app";
const admin = initializeApp({
credential: refreshToken({
refresh_token: account.tokens.refresh_token,
}),
});
但是,它现在引发错误,指出它缺少
client_secret
和 client_id
属性,而 account
对象没有这些属性。 AFAIK,只有服务帐户才有这些。
所以我发现通过使用
GOOGLE_APPLICATION_CREDENTIALS
这是可能的。
Firebase Tools 有一个名为
getCredentialPathAsync()
的方法,据我所知,它会在您的计算机上的某个位置找到一个凭据文件,如果没有,它会生成一个凭据文件,然后返回路径。您可以将 GOOGLE_APPLICATION_CREDENTIALS
设置为该文件的位置。
import { getGlobalDefaultAccount } from "firebase-tools/lib/auth.js";
import { getCredentialPathAsync } from "firebase-tools/lib/defaultCredentials.js";
import { initializeApp } from "firebase-admin/app";
async function main() {
const account = getGlobalDefaultAccount() // Get the logged in account
const credPath = await getCredentialPathAsync(account) // Get the path
process.env.GOOGLE_APPLICATION_CREDENTIALS = credPath // Set the environment variable
const firebaseApp = initializeApp({
projectId: "PROJECT_ID",
}) // Initialize the Admin SDK
}
main()