获取授权用户的 Firebase CLI 权限

Firebase CLI permission to get auth users

安装 Firebase CLI 并登录后,我可以像这样创建一个 JavaScript 文件,从 Firestore 检索数据并直接从本地命令行执行它:

script.js:

const admin = require('firebase-admin');

(async () => {
  admin.initializeApp({ projectId: 'my-project-id' });

  const widget = await admin
    .firestore()
    .doc('widgets/someid')
    .get();

  console.log(widget.data());
})();

命令:node script.js

在我尝试从 Firebase 的身份验证中检索用户之前,它工作得很好。然后我遇到了 403 错误。这是脚本:

const admin = require('firebase-admin');

(async () => {
  admin.initializeApp({ projectId: 'my-project-id' });

  const user = await admin
    .auth()
    .getUser('some-uid');

  console.log(user);
})();

错误信息如下:

{
    "error": {
        "code": 403,
        "message": "Your application has authenticated using end user credentials from the Google Cloud SDK or Google Cloud Shell which are not supported by the identitytoolkit.googleapis.com.We recommend configuring the billing / quota_project setting in gcloud or using a service account through the auth / impersonate_service_account setting.For more information about service accounts and how to use them in your application, see https: //cloud.google.com/docs/authentication/.",
        "errors": [{
            "message": "Your application has authenticated using end user credentials from the Google Cloud SDK or Google Cloud Shell which are not supported by the identitytoolkit.googleapis.com. We recommend configuring the billing/quota_project setting in gcloud or using a service account through the auth/impersonate_service_account setting. For more information about service accounts and how to use them in your application, see https://cloud.google.com/docs/authentication/.",
            "domain": "usageLimits",
            "reason": "accessNotConfigured",
            "extendedHelp": "https://console.developers.google.com"
        }],
        "status": "PERMISSION_DENIED"
    }
}

这很奇怪,因为我是以 GCP 项目的管理员身份登录的。上面的代码在 运行 云函数内部时也能很好地工作(它只有我所拥有的一部分权限)。如何更改权限和配置以使上述脚本正常工作?

正如@Jordi 在评论中提到的,您需要创建一个服务帐户并在我的 shell 中激活该服务帐户才能访问 firebase 身份验证。

步骤如下:

在 Google Cloud Console 中,创建一个新的服务帐户。授予 Firebase Authentication AdminCloud Datastore Owner 角色:

生成新密钥并在本地存储 JSON 文件:

使用服务帐户凭据:

Mac/Linux:

export GOOGLE_APPLICATION_CREDENTIALS=./path/service-account.json

Windows:

$env:GOOGLE_APPLICATION_CREDENTIALS = './path/service-account.json'

现在您可以使用正确的凭据执行调用 firebase-adminadmin.auth() 以及 admin.firestore() 的节点脚本:

node script.js