# Build a Multi-Tenant SaaS Application With FusionAuth

Learn how to build a multi-tenant SaaS application that creates a FusionAuth Tenant for each customer and routes logins by hostname.

> For the index of this section of the site, see [llms.txt](https://fusionauth.io/docs/llms.txt)

In this tutorial, you build the PiedPiper Video Chat (PPVC) multi-tenant application. FusionAuth stores the users of the control plane application and of every data plane application. When a customer signs up, PPVC creates a FusionAuth Tenant, a Tenant-locked API key, and a FusionAuth Application for the customer. PPVC then routes each login to the right Tenant based on the hostname.

For the concepts behind this tutorial, such as the control plane, the data plane, and the tenant object, see [Multi-Tenancy](https://fusionauth.io/docs/concepts/patterns/multi-tenant.md).

You build the following parts:

*   A FusionAuth Application for the control plane application, with sign up and login through FusionAuth.
*   A `tenant` table in your database, an object in your web application codebase, and methods to create, read, update, and delete the object.
*   Code that creates, modifies, and deletes FusionAuth configuration for each data plane application.
*   Login, registration, and logout URLs that send each request to the correct FusionAuth Tenant.
*   Callback handling for the Authorization Code grant in your web application codebase.

The examples use PHP. To review and run the finished code, download the [multi-tenant chat application](https://github.com/FusionAuth/fusionauth-example-symfony-multitenant). The application doesn't include video chat.

## Prerequisites

You need the following:

*   A running FusionAuth instance and access to the Admin UI.
*   A web application codebase with a database, and an OAuth library for your framework.
*   A [FusionAuth client library](https://fusionauth.io/docs/sdks.md). The examples use the PHP client library. You can use any client library, or call the [APIs](https://fusionauth.io/docs/apis.md) directly with JSON objects.
*   Control over DNS for your domain, or the ability to edit your `/etc/hosts` file for local development.

## Configure FusionAuth for the Control Plane

The control plane application needs a FusionAuth Application. Put the Application in a separate FusionAuth Tenant to increase isolation.

To skip the manual steps, download the [multi-tenant control plane Kickstart file](https://github.com/FusionAuth/fusionauth-example-kickstart/blob/main/multi-tenant-control-plane/kickstart.json), customize the file, and run the file with [Kickstart](https://fusionauth.io/docs/get-started/develop/kickstart.md).

1.  Create a Tenant for the control plane application, and create an Application in the Tenant. On the OAuth tab of the Application, add an authorized [redirect URL](https://fusionauth.io/docs/authentication/oauth/url-validation.md) and enable the Authorization Code grant. Add Roles to the Application when you need them.
    
    ![The control plane Application in the FusionAuth Admin UI.](https://fusionauth.io/img/docs/screenshots/first-time-setup-application-form.png)
    
2.  When users sign up for the control plane application themselves, enable self-service registration on the Registration tab. Otherwise, create the users another way, such as with the [User API](https://fusionauth.io/docs/apis/users.md).
    
    ![The Registration tab of the control plane Application, with self-service registration turned on.](https://fusionauth.io/img/docs/screenshots/multi-tenant-control-plane-registration.png)
    
3.  Configure your control plane application to use FusionAuth for authentication. The steps depend on your framework, and usually involve an OAuth library.
    
4.  Create a key manager API key. Navigate to Settings -> API Keys and create a global API key. Enable **Allow this key to manage other keys**, because PPVC uses the key to create Tenant-locked API keys.
    
    ![The Add API Key form for a key manager API key.](https://fusionauth.io/img/docs/screenshots/multi-tenant-key-manager.png)
    
5.  Create a separate Tenant to serve as a blueprint. The blueprint Tenant provides the default settings for every data plane FusionAuth Tenant. Configure the email server, password complexity, and other settings. You can still customize the settings for each Tenant later, but a blueprint to copy makes data plane Tenant setup easier.
    
    ![The Add Tenant form for the blueprint Tenant.](https://fusionauth.io/img/docs/screenshots/multi-tenant-blueprint-tenant.png)
    

## Define the Tenant Object

The tenant object stores every piece of tenant information, from FusionAuth or from your application. Both the control plane and the data plane applications use the object. For the attributes the object needs, see [The Tenant Object](https://fusionauth.io/docs/concepts/patterns/multi-tenant.md#the-tenant-object).

The following DDL creates a sample `tenant` table:

Tenant object creation DDL

```sql
 CREATE TABLE tenant
             (
                          id                    INT NOT NULL auto_increment,
                          user_id               INT NOT NULL,
                          hostname              VARCHAR(255) collate utf8mb4_unicode_ci NOT NULL,
                          background_color_code VARCHAR(6) COLLATE utf8mb4_unicode_ci NOT NULL,
                          fusion_auth_tenant_id VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL,
                          api_key               VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL,
                          api_key_id            VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL,
                          client_id             VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL,
                          client_secret         VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL,
                          PRIMARY KEY (id),
                          UNIQUE KEY uniq_4e59c462a76ed395 (user_id),
                          UNIQUE KEY uniq_6459cd6da86ed443 (hostname),
                          CONSTRAINT fk_4e59c462a76ed395 FOREIGN KEY (user_id) REFERENCES user (id)
             )
             engine=innodb DEFAULT charset=utf8mb4 COLLATE=utf8mb4_unicode_ci
```

The `user_id` column is a foreign key into the local `user` table, so this table maps each tenant to a single user. You can also let one user create more than one tenant. Build a user interface to manage this data.

Note

As an alternative, you can capture tenant setup information, such as the hostname, at registration with [Advanced Registration Forms](https://fusionauth.io/docs/users/register/advanced-registration-forms.md), a premium feature. A webhook can then create the FusionAuth configuration and the tenant object in the web application database.

PPVC uses the `hostname` column throughout. The `hostname` value tells the code which data plane application, and which Tenant, a request belongs to, so the column is unique. You can let the user pick the hostname, such as `hooli`, or assign a hostname, such as `tenant123`. PPVC prepends the `hostname` to the domain name, `piedpipervideochat.com`, to build the address where end users of PPVC chat.

You can also let a customer use an entirely different host and domain name, such as `chat.hooli.com`. That option makes a good premium feature, but needs more setup, and this tutorial doesn't cover the option.

The table has the following FusionAuth columns:

*   `fusion_auth_tenant_id`: The UUID of the FusionAuth Tenant.
*   `api_key`: A Tenant-locked API key.
*   `api_key_id`: The Id of the Tenant-locked API key. You use the Id to manage the API key.
*   `client_id`: The Client Id of the data plane FusionAuth Application.
*   `client_secret`: The Client Secret of the data plane FusionAuth Application.

## Create FusionAuth Configuration for Each Tenant

To keep FusionAuth and your application in sync, create the FusionAuth configuration for a data plane application when PPVC creates the application. Delete the configuration when PPVC removes the application.

You can call the FusionAuth APIs at the following points:

*   In the controller that creates the row in the `tenant` table. Call the APIs and wait for the APIs to return.
*   From a queue. Put a message on the queue when PPVC adds a tenant row, and have a listener read the message and create the configuration.
*   From a framework-specific hook that runs before the framework saves or deletes the tenant.

PPVC uses the framework hook. Before PPVC saves the tenant to the database, PPVC calls the FusionAuth APIs and creates the FusionAuth configuration. The right choice depends on how many tenants you expect and how much configuration each tenant needs. For example, when PPVC imports many users for each new data plane application, asynchronous execution works better.

A data plane application needs at least a FusionAuth Tenant based on the blueprint Tenant, a Tenant-locked API key, and a FusionAuth Application. Store the generated values in the tenant object of the data plane application.

1.  Create the FusionAuth Tenant. Retrieve the blueprint Tenant, extract the default configuration, and create the new Tenant:
    
    ```php
    $fusionauthBase = 'http://login.piedpipervideochat.com/'; // or pull from config
    $client = new FusionAuthClient($fusionauthKeyManagerKey, $fusionauthBase);
    
    $result = $client->retrieveTenant($this->blueprintTenantId);
    if (!$result->wasSuccessful()) {
      $this->logger->error('An error occurred!');
      $this->logger->error(var_export($result,TRUE));
      throw new FusionAuthException("Can't save: ".var_export($result,TRUE));
    }
    
    $blueprint_tenant = $result->successResponse;
    
    // pick off what we know we want to minimize forward compatibility issues.
    
    $tenant_object = array();
    $tenant_object["name"] = $tenant->getHostname();
    $tenant_object["themeId"] = $blueprint_tenant->tenant->themeId;
    $tenant_object["issuer"] = 'https://'.$tenant->getHostname().".ppvc.com";
    
    $tenant_email_configuration = $this->convertObjectToArray($blueprint_tenant->tenant->emailConfiguration);
    $tenant_object["emailConfiguration"] = $tenant_email_configuration;
    
    $tenant_jwt_configuration = $this->convertObjectToArray($blueprint_tenant->tenant->jwtConfiguration);
    $tenant_object["jwtConfiguration"] = $tenant_jwt_configuration;
    
    $tenant_externalId_configuration = $this->convertObjectToArray($blueprint_tenant->tenant->externalIdentifierConfiguration);
    $tenant_object["externalIdentifierConfiguration"] = $tenant_externalId_configuration;
    
    $tenant_request = array();
    $tenant_request["tenant"] = $tenant_object;
    
    $result = $client->createTenant('', $tenant_request);
    if (!$result->wasSuccessful()) {
      $this->logger->error('An error occurred!');
      $this->logger->error(var_export($result,TRUE));
      throw new FusionAuthException("Can't save: ".var_export($result,TRUE));
    }
    
    $new_tenant = $result->successResponse;
    return $new_tenant->tenant->id;
    ```
    
    The code copies the following configuration from the blueprint Tenant:
    
    *   `themeId`
    *   `emailConfiguration`
    *   `jwtConfiguration`
    *   `externalIdentifierConfiguration`
    
    The new data plane Tenant differs from the blueprint Tenant in the following values:
    
    *   The name of the Tenant, which the code sets to the hostname.
    *   The issuer, which the code sets to the expected host.
    
    As an alternative, copy the blueprint Tenant and then patch the differences. Either way, you can change any other Tenant setting. For example, when your tenants have different password complexity rules, set the rules when you create the FusionAuth Tenant, so FusionAuth applies the rules consistently.
    
    Store the FusionAuth Tenant Id in the `tenant` table.
    
2.  Create a Tenant-locked API key. A Tenant-locked API key has the following benefits:
    
    *   You can use the key for further configuration of the Tenant. The key follows the principle of least privilege, so you can't affect other Tenants by mistake.
    *   You can show the key to your customers. Your customers can then write scripts against FusionAuth for their own needs, such as managing users. The key adds value at low cost and makes PPVC stickier.
    
    The following code creates the Tenant-scoped API key:
    
    ```php
    $apikey_object = array();
    $apikey_object["metaData"]["attributes"]["description"] = "API key for ".$hostname;
    $apikey_object["tenantId"] = $fusionauth_tenant_id;
    
    $apikey_request = array();
    $apikey_request["apiKey"] = $apikey_object;
    
    $result = $client->createAPIKey('', $apikey_request);
    if (!$result->wasSuccessful()) {
      $this->logger->error('An error occurred!');
      $this->logger->error(var_export($result,TRUE));
      throw new FusionAuthException("Can't save: ".var_export($result,TRUE));
    }
    
    $apikey = $result->successResponse;
    
    return [$apikey->apiKey->id, $apikey->apiKey->key];
    ```
    
    Store the key and the key Id in the `tenant` table. You use the key for other API calls, and the key Id to modify the key later.
    
3.  Create a FusionAuth client that uses the Tenant-locked key, which has fewer permissions than the key manager key:
    
    ```php
    $fusionauthTenantLockedApiKey = '...'; // returned from the previous code block
    $fusionauthBase = 'http://login.piedpipervideochat.com/'; // or pull from config
    $client = null;
    $client = new FusionAuthClient($fusionauthTenantLockedApiKey, $fusionauthBase);
    ```
    
4.  Create the FusionAuth Application. Every app that a user logs in to needs a FusionAuth Application. For example, users such as Patrice or Jason Winter log in to the Hooli instance of PPVC. The Application configuration includes several URLs, so the code needs the hostname, `hooli`:
    
    ```php
    $saasRootDomain = '.piedpipervideochat.com'; // or pull from config
    $ppvc_app_base = "https://".$hostname.$saasRootDomain;
    
    $application_object = array();
    $application_object["name"] = "Default application for ".$hostname;
    
    $application_oauthconfiguration = array();
    $application_oauthconfiguration["authorizedRedirectURLs"] = [$ppvc_app_base."/login/callback"];
    $application_oauthconfiguration["enabledGrants"] = ["authorization_code"];
    $application_oauthconfiguration["logoutURL"] = $ppvc_app_base;
    $application_object["oauthConfiguration"] = $application_oauthconfiguration;
    
    $application_registrationconfiguration = array();
    $application_registrationconfiguration["enabled"] = true;
    $application_object["registrationConfiguration"] = $application_registrationconfiguration;
    
    $application_request = array();
    $application_request["application"] = $application_object;
    
    $result = $client->createApplication('', $application_request);
    if (!$result->wasSuccessful()) {
      $this->logger->error('An error occurred!');
      $this->logger->error(var_export($result,TRUE));
      throw new FusionAuthException("Can't save: ".var_export($result,TRUE));
    }
    
    $application = $result->successResponse;
    
    return [$application->application->id, $application->application->oauthConfiguration->clientSecret];
    ```
    
    The code builds a base URL such as `https://hooli.piedpipervideochat.com`. Every URL and other data plane setting builds on the base URL.
    
    Users log in to the data plane application with the Authorization Code grant, so the code sets up **`oauthConfiguration`**. The code does the following:
    
    *   Enables the Authorization Code grant in **`enabledGrants`**.
    *   Sets **`logoutURL`**, where FusionAuth sends the user after logout.
    *   Adds the callback URL to **`authorizedRedirectURLs`**. You write the callback code in [Handle the OAuth Callback](#handle-the-oauth-callback).
    
    The code also enables basic self-service registration in **`registrationConfiguration`**. After the data plane application goes live, the Hooli users need accounts. You have the following options:
    
    *   Let users log in with a social provider.
    *   Create users with the FusionAuth API and an automated process.
    *   Let users log in with an enterprise SSO provider, such as an OAuth or SAML Identity Provider.
    *   Let users sign up for an account.
    
    You can configure any of these options. For example, to let users log in with Google, create an Identity Provider during [Configure FusionAuth for the Control Plane](#configure-fusionauth-for-the-control-plane). Then assign the Identity Provider to the FusionAuth Application of each new data plane application.
    
5.  Store the Id and the Client Secret of the FusionAuth Application in the `tenant` table. Later steps need these values.
    

These steps create every required piece of configuration for a user to sign up or log in to a PPVC data plane application. You might also want to do the following:

*   Add a user or a set of users.
*   Create FusionAuth Registrations for the users, so the users can log in.
*   Set up Roles.
*   Set up Groups.
*   Assign users to Groups and Roles.
*   Create FusionAuth API keys with limited permissions, such as a read-only user query key.

## Route Requests to the Correct Tenant

PPVC now creates a FusionAuth Tenant and Application every time a user registers in the control plane application. Next, map each request to a data plane application. PPVC uses the hostname to find the tenant: `hooli.piedpipervideochat.com` points to the Hooli data plane application. For other ways to find the tenant, see [Data Plane Application Tenant Determination](https://fusionauth.io/docs/concepts/patterns/multi-tenant.md#data-plane-application-tenant-determination).

1.  Configure DNS to send every request for a host ending in `.piedpipervideochat.com` to your web application. For how to point a wildcard DNS entry at a host, see the documentation of your DNS provider. When you develop locally, add the hostnames to your `/etc/hosts` file:
    
    ```plaintext
    127.0.0.1       localhost app.piedpipervideochat.com raviga.piedpipervideochat.com hooli.piedpipervideochat.com
    ```
    
2.  Configure your web server to accept requests for every hostname. For the steps, see the documentation of your web server. The following Apache configuration sends traffic for every `piedpipervideochat.com` address to a proxied local web application on port 8000:
    
    ```apacheconf
    <VirtualHost *:443>
      ServerName app.piedpipervideochat.com
      ServerAlias *.piedpipervideochat.com
    
      ProxyPreserveHost on
      ProxyPass / http://localhost:8000/ retry=1
      ProxyPassReverse / http://localhost:8000/ retry=1
    </VirtualHost>
    ```
    
    Pass the `Host` header through to the web application code. The web application uses the header to look up the tenant object.
    
3.  Look up the OAuth configuration based on the hostname. When your web application receives a request, find the Client Id and Client Secret in the `tenant` table by the hostname of the request. For a request to `https://hooli.piedpipervideochat.com/login`, map the hostname, `hooli`, to the Client Id:
    
    ```php
    $client_id = '';
    $client_secret = '';
    
    if ($this->isControlPlaneHost($host)) {
      $client_id = $this->controlPlaneClientId;
      $client_secret = $this->controlPlaneClientSecret;
    } else {
      $hostname = $this->hostname($host); // converts from hooli.piedpipervideochat.com to hooli
      $repository = $this->entityManager->getRepository(Tenant::class);
      $tenant = $repository->findOneBy(array('hostname'=>$hostname));
      if ($tenant) {
        $client_id = $tenant->getApplicationId();
        $client_secret = $tenant->getClientSecret();
      } else {
        // throw an error, this is not a valid hostname. Doing so will allow an attacker to enumerate your supported hostnames, however.
      }
    }
    return [$client_id, $client_secret];
    ```
    
    The code first checks whether the host is the control plane application. The PPVC web application answers every request. The requests come from users who log in to the control plane application to create video chat tenants, and from users who log in to a data plane application to chat.
    
    The OAuth configuration of the control plane application is static. You created the configuration in [Configure FusionAuth for the Control Plane](#configure-fusionauth-for-the-control-plane). The configuration of each data plane application is dynamic and lives in the database. You created the configuration in [Create FusionAuth Configuration for Each Tenant](#create-fusionauth-configuration-for-each-tenant). The code retrieves the tenant object by hostname and returns the Client Id and Client Secret.
    
    Each FusionAuth Application belongs to exactly one FusionAuth Tenant. The Client Id identifies the FusionAuth Application, so FusionAuth finds the correct Tenant from the Client Id. PPVC uses the Client Id to build the login, logout, and registration links. Use the links in navigation or anywhere else a user might log in, register, or log out.
    
4.  Build the links. The following code builds a simplified login link from the FusionAuth OAuth endpoints and the retrieved `client_id`, without a library:
    
    ```php
    $redirectURI = '...'; // discussed below.
    $fusionauthBase = 'http://login.piedpipervideochat.com/'; // or pull from config
    return $fusionauthBase . '/oauth2/authorize?client_id='.$client_id.'&redirect_uri='.$redirectURI.'&response_type=code'
    ```
    
    The registration URL has the same format, with the path `/oauth2/register` instead of `/oauth2/authorize`:
    
    ```php
    $redirectURI = '...'; // discussed below.
    $fusionauthBase = 'http://login.piedpipervideochat.com/'; // or pull from config
    return $fusionauthBase . '/oauth2/register?client_id='.$client_id.'&redirect_uri='.$redirectURI.'&response_type=code'
    ```
    
    Logout must end the session in FusionAuth and in your control plane or data plane application. The FusionAuth Application sets **`logoutURL`**. When the user visits the logout URL, FusionAuth logs the user out of FusionAuth and then redirects the user to the **`logoutURL`** location. The code at that location must log the user out of the control plane or data plane application, such as by ending the session.
    
    ```php
    $fusionauthBase = 'http://login.piedpipervideochat.com/'; // or pull from config
    $fusionauthBase.'/oauth2/logout?client_id='.$clientId;
    ```
    
    The logout URL works with browsers. When a mobile application uses the APIs, revoke the refresh token instead of calling the `/oauth2/logout` endpoint.
    

Tip

The sample PPVC application uses an open source library to build OAuth URLs. The library sets the `state` parameter and handles other details. When your framework or language has such a library, use the library.

## Handle the OAuth Callback

The last step for multiple Tenants is the OAuth callback. In [Create FusionAuth Configuration for Each Tenant](#create-fusionauth-configuration-for-each-tenant), you set **`authorizedRedirectURLs`** on the FusionAuth Application to a value such as `https://hooli.piedpipervideochat.com/login/callback`. The same value goes in `$redirectURI = '...';` in the link code.

Write code in your web application to answer OAuth redirect requests:

1.  Determine the OAuth configuration of the tenant. Map the hostname, such as `hooli`, to the Client Id and Client Secret, with the same logic as the hostname lookup in [Route Requests to the Correct Tenant](#route-requests-to-the-correct-tenant).
    
2.  Exchange the authorization code for a token. Use an OAuth library for your language or framework, or the FusionAuth client library:
    
    ```php
    $fusionauthBase = 'http://login.piedpipervideochat.com/'; // or pull from config
    $noApiKeyNeeded = '';
    $client = new FusionAuthClient($noApiKeyNeeded, $fusionauthBase);
    
    $result = $client->exchangeOAuthCodeForAccessToken($code, $client_id, $client_secret, $redirect_uri)
    if (!$result->wasSuccessful()) {
      $this->logger->error('An error occurred!');
      $this->logger->error(var_export($result,TRUE));
      throw new FusionAuthException("Can't save: ".var_export($result,TRUE));
    }
    
    $oauthResult = $result->successResponse;
    
    $token = $oauthResult->access_token;
    ```
    
3.  Log the user in. You now have an access token for an authenticated user. Examine the token to check that the user is authorized for the FusionAuth Application. You can also examine the Roles of the user and show or hide functionality based on the Roles.
    
    Create a login session in your web application. The steps depend on your framework or programming language.
    
    You can also create or update a local user record in your database. When other parts of the web application relate to a user, a local user record is common, and many frameworks expect one. For how to handle duplicate email addresses across Tenants, see [Framework Specific User Objects](https://fusionauth.io/docs/concepts/patterns/multi-tenant.md#framework-specific-user-objects).
    
4.  Redirect the user. Check the hostname. Send a data plane user to the chat page, and send a control plane user to a profile page.
    

When you call the FusionAuth API for a tenant, send the Tenant Id. For more information, see [API Calls](https://fusionauth.io/docs/concepts/patterns/multi-tenant.md#api-calls).

Related

[Concepts Multi-tenancy Learn how to run multiple tenants in a single FusionAuth instance. multi-tenancysaasmulti-tenant setup](https://fusionauth.io/docs/concepts/patterns/multi-tenant.md)

[Concepts Universal Applications Learn about universal Applications, which every Tenant can use, and how universal Applications differ from Applications that belong to one Tenant. multi-tenancysaas](https://fusionauth.io/docs/concepts/types/universal-applications.md)

[Authentication Add FusionAuth Login to an External Application Learn how to let users log in to a third-party application, such as a SaaS product, with their FusionAuth accounts over OpenID Connect or SAML v2. saas](https://fusionauth.io/docs/authentication/act-as-an-idp/add-login-to-external-app.md)

[Concepts Modeling Organizations Using the FusionAuth Entity Management feature to model organizations and users that belong to organizations. saas](https://fusionauth.io/docs/concepts/patterns/modeling-organizations.md)
---

## Other pages in Multi Tenant

> For the full index of this section, see [Concepts](https://fusionauth.io/docs/llms-concepts.txt).

- [Multi-tenancy](https://fusionauth.io/docs/concepts/patterns/multi-tenant.md): Learn how to run multiple tenants in a single FusionAuth instance.
