更改 firebase-admin 的 verifyIdToken 中的预期“受众”

Guy*_*Guy 8 node.js google-signin firebase-admin

我们正在尝试在我们的移动应用程序中实现Google 登录按钮,并将idToken发送到我们的NodeJS服务器以完成身份验证过程。移动应用程序上的生成按预期工作,但使用firebase-adminidToken在服务器端验证令牌会引发受众不匹配错误。

方法#1

在我们的 NodeJS 服务器中使用google-auth-library可以按预期工作(最小示例):

import { OAuth2Client } from 'google-auth-library';

const client = new OAuth2Client(credentials.client_id);

(async () => {
    const ticket = await client.verifyIdToken({
            idToken: token,
            audience: [
                credentials.client_id,
                'xyz.apps.googleusercontent.com',   <===== clientId added here
            ],
        });

    const payload = ticket.getPayload();
    console.log(payload); //  GOOD! idToken verification successful!
})();
Run Code Online (Sandbox Code Playgroud)

它之所以有效,是因为我们手动添加移动应用程序client id中指定的移动设备。google-services.json

方法#2

由于我们更愿意使用firebase-admin包,因此我们想知道是否audience可以对 SDK 的verifyIdToken方法进行类似的添加。目前这不起作用:

import admin from 'firebase-admin';

const serviceAccount = fs.readJsonSync('./service-account.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
});

(async () => {
    const userInfo = await admin.auth().verifyIdToken(token);
    console.log(userInfo);  // ERROR! Verification throws error!
})();
Run Code Online (Sandbox Code Playgroud)

它抛出以下错误:

错误:Firebase ID 令牌的“aud”(受众)声明不正确。应为“xyz-123”,但得到“xyz.apps.googleusercontent.com”。确保 ID 令牌与用于验证此 SDK 的服务帐户来自同一个 Firebase 项目

我们做了多次尝试:

  1. clientId更改移动设备上组件中的m Sign-In with Google。
  2. 更改服务帐户中的值nodeJs。

这些尝试的结果是未生成令牌或我们遇到了所描述的不匹配验证错误。

关于按照方法 #1中所述手动添加受众值,源代码似乎没有提供提供更多受众的方法。

  1. 是否有原因导致添加受众的选项在 中被省略firebase-admin而在 中可用google-auth-library?
  2. audiences在验证id tokens包时是否有不同的方法来更改预期firebase-admin?

off*_*fex 0

我刚刚遇到了类似的问题并通过使用解决了它

// gets firebase id token
const idToken = await result.user.getIdToken();
Run Code Online (Sandbox Code Playgroud)

代替

// gets original id token
const idToken = await GoogleAuthProvider.credentialFromResult(result).idToken;
Run Code Online (Sandbox Code Playgroud)