Search code examples
firebasegoogle-cloud-platformfirebase-authentication

How to generate firebase custom tokens in multi tenant setup


I have been trying to add support for multi tenants to my application.

I initialize like so

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

Part of my application then uses the auth.createCustomToken(uid) in order to create a token that can then be exchanged for a standard id token (Using the rest endpoint /accounts:signInWithCustomToken.

When trying to create the custom token I get the following error

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

Additionally to this when manually creating a token (using jsonwebtoken and the service account key) the error

Specified tenant ID does not match the custom token

Comes up when attempting to verify the token (through the REST API)

Has anyone else encountered this error, or is anyone aware of another way to generate and verify custom tokens in a multi tenant environment (or, alternatively, know of some way to log a user in given only a uid)?


Solution

  • This question is old, and hence the previous answers are kinda obsolete. Now, you can create a token by setting the tenant-id in the Auth object, both on the Admin SDK and the Firebase Auth Client.

    On Admin SDK:

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

    On Firebase Auth Client:

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

    As long as the Tenant-Id matches, you should not see any issues. You don't need to use any third-party library anymore unless your language is not supported.