Firebase CLI:对 Firebase 模拟器执行任意 Firebase 身份验证请求

Firebase CLI: execute arbitrary Firebase Authentication requests to Firebase Emulator

使用 Firebase CLI,我正在执行存储在文件中的任意 JavaScript。在该脚本中,我尝试调用 admin.auth().something(),但它不适用于 Firebase 模拟器。这与调用 Firestore 形成对比,Firestore 与模拟器完美配合。

Firestore(一切正常)

GCP

这会调用 GCP 上的 Firestore 并成功:

const admin = require('firebase-admin');
admin.initializeApp({ projectId: 'my-project' });
const db = admin.firestore();

(async () => {
  const widget = await db.doc('/widgets/123456789').get();
  console.log(widget.data().name);
})();

模拟器

这也成功了:

const admin = require('@firebase/testing');
const db = admin
  .initializeAdminApp({ projectId: 'my-project' })
  .firestore();

(async () => {
  const widget = await db.doc('/widgets/123456789').get();
  console.log(widget.data().name);
})();

Firebase 身份验证(GCP 可用但模拟器不可用)

GCP

这会在 GCP 上调用 Firebase Auth 并成功:

const admin = require('firebase-admin');
admin.initializeApp({ projectId: 'my-project' });

(async () => {
  const user = await admin
    .auth()
    .getUser('user123456789');

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

模拟器

这失败了:

const admin = require('@firebase/testing');
const auth = admin
  .initializeAdminApp({ projectId: 'my-project' })
  .auth();

(async () => {
  const user = await auth.getUser('user123456789');

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

错误信息是:

C:\Users\...\node_modules\@firebase\testing\node_modules\@firebase\component\dist\index.cjs.js:134
                throw e;
                ^
[t [Error]: Your API key is invalid, please check you have copied it correctly.] {
  code: 'auth/invalid-api-key',
  a: null
}

我不确定他们指的是什么 API 密钥,因为该请求是针对模拟器的。如何使用 Firebase CLI 对模拟器执行 Firebase Auth 请求?

要针对 Firebase Emulator Auth 发送请求,请设置以下环境变量并使用标准 Firebase Admin SDK (firebase-admin) 而不是使用 @firebase/testing:

process.env.FIREBASE_AUTH_EMULATOR_HOST = 'localhost:9099';
process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8080';

const admin = require('firebase-admin');
admin.initializeApp({ projectId: 'emulator projectId' });

现在可以了:

(async () => {
  const user = await auth.getUser('user123456789');

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