如何在多租户设置中生成 Firebase 自定义令牌

问题描述 投票:0回答:3

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

我像这样初始化

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 令牌(使用其余端点
/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 的情况下登录用户的某种方法)?

firebase google-cloud-platform firebase-authentication
3个回答
2
投票

这个问题很老了,因此之前的答案有点过时了。 现在,您可以通过在 Admin SDK 和 Firebase Auth 客户端上的 Auth 对象中设置租户 ID 来创建令牌。

在管理 SDK 上:

  const auth = admin.auth().tenantManager().authForTenant(<tenant-id-value>);
  const firebaseToken = await auth.createCustomToken(uid);
  return firebaseToken; // send firebaseToken to client

在 Firebase 身份验证客户端上:

const auth = firebase.auth();
auth.tenantId = <tenant-id-value>;
auth.signInWithCustomToken(firebaseToken);

只要租户 ID 匹配,您就不应该看到任何问题。除非您的语言不受支持,否则您不需要再使用任何第三方库。


2
投票

更新:请使用Sundeep的答案,这个答案是在没有可用的官方选项时给出的。从长远来看,Sundeep 的答案应该更加稳健

================

不要使用 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 to

将自定义令牌交换为 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身份验证文档中)在撰写本文时)


-1
投票

当前多租户环境中不支持自定义令牌身份验证。此功能仍正在建设中。您可以在此处查看支持功能的完整列表。

© www.soinside.com 2019 - 2024. All rights reserved.