首页 > 解决方案 > 如何在多租户设置中生成 Firebase 自定义令牌

问题描述

我一直在尝试为我的应用程序添加对多租户的支持。

我这样初始化

const app = firebase.initializeApp();
const tenantManager = app.auth().tenantManager();
const tenant = await tenantManager.createTenant({ displayName: `test- tenant` });
const auth = tenantManager.authForTenant(tenantId);

然后,我的应用程序的一部分使用auth.createCustomToken(uid)来创建一个令牌,然后可以将其交换为标准 id 令牌(使用 rest 端点/accounts:signInWithCustomToken.

尝试创建自定义令牌时出现以下错误

Error: This operation is not supported in a multi-tenant context

除此之外,在手动创建令牌(使用jsonwebtoken和服务帐户密钥)时出现错误

Specified tenant ID does not match the custom token

尝试验证令牌时出现(通过 REST API)

是否有其他人遇到过此错误,或者是否有人知道在多租户环境中生成和验证自定义令牌的另一种方法(或者,知道某种方法可以仅在给定 uid 的情况下让用户登录)?

标签: firebasegoogle-cloud-platformfirebase-authentication

解决方案


不要使用 API 生成自定义令牌,而是使用服务帐户生成一个JWT用于private_key签名并确保您具有下面定义的值

const jwt = require(`jsonwebtoken`);
const payload = {
    uid,
    sub: serviceAccount.client_email,
    tenant_id: tenantId
};
jwt.sign(payload, serviceAccount.private_key, {
    audience: `https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit`,
    issuer: serviceAccount.client_email,
    algorithm: `RS256`,
    expiresIn: 0
});

注意:tenant_id有效载荷中的 。

POST现在,当通过ing将自定义令牌交换为 firebase 颁发的令牌时

`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${encodeURIComponent(webApiKey)}`

确保它tenantId是请求的 JSON 正文中的一个属性,并且与tenant_id令牌中找到的相匹配。

{
    tenantId, // Make sure this matches the "tenant_id" claim in the idToken
    token: idToken,
    returnSecureToken: true
}

第二部分记录在https://cloud.google.com/identity-platform/docs/reference/rest/client/#section-verify-custom-token(但当时不在原始的firebase auth文档中这篇文章的)


推荐阅读