Multitenancy With Spring Data JPA
1. Overview
Multi-tenancy refers to an architecture in which a single instance of a software application serves multiple tenants or customers.
It enables the required degree of isolation between tenants so that the data and resources used by tenants are separated from the others.
In this tutorial, we'll see how to configure multi-tenancy in a Spring Boot application with Spring Data JPA. Also, we add security to tenants using JWT.
2. Multi-Tenancy Models
There are three main approaches to multi-tenant systems:
- Separate Database
- Shared Database and Separate Schema
- Shared Database and Shared Schema
2.1. Separate Database
In this approach, each tenant’s data is kept in a separate database instance and is isolated from other tenants. This is also known as Database per Tenant:
2.2. Shared Database and Separate Schema
In this approach, each tenant’s data is kept in a distinct schema on a shared database. This is sometimes called Schema per Tenant:
2.3. Shared Database and Shared Schema
In this approach, all tenants share a database, and every table has a column with the tenant identifier:
3. Maven Dependencies
Let's start by declaring spring-boot-starter-data-jpa dependency in a Spring Boot application in the pom.xml:
Also, we'll be using a PostgreSQL database, so let's also add postgresql dependency to the pom.xml file:
The Separate Database and Shared Database and Separate Schema approaches are similar in the configuration in a Spring Boot application. In this tutorial, we focus on the Separate Database approach.
4. Dynamic DataSource Routing
In this section, we'll describe the general idea behind the Database per Tenant model.
4.1. AbstractRoutingDataSource
The general idea to implement multi-tenancy with Spring Data JPA is routing data sources at runtime based on the current tenant identifier.
In order to do that, we can use AbstractRoutingDatasource as a way of dynamically determining the actual DataSource based on the current tenant.
Let's create a MultitenantDataSource class that extends the AbstractRoutingDataSource class:
The AbstractRoutingDataSource routes getConnection calls to one of the various target DataSources based on a lookup key.
The lookup key is usually determined through some thread-bound transaction context. So, we create a TenantContext class for storing the current tenant in each request:
We use a ThreadLocal object for keeping the tenant ID for the current request. Also, we use the set method to store the tenant ID and the get() method to retrieve it.
4.2. Setting Tenant ID per Request
After this configuration setup, when we perform any tenant operation, we need to know the tenant ID before creating any transaction. So, we need to set the tenant ID in a Filter or Interceptor before hitting controller endpoints.
Let's add a TenantFilter for setting the current tenant in TenantContext:
In this filter, we get the tenant ID from the request header X-TenantID and set it in TenantContext. We pass control down the chain of filters. Our finally block ensures that the current tenant is reset before the next request. This avoids any risk of cross-tenant request contamination.
In the next section, we'll implement the tenants and data source declaration in the Database per Tenant model.
5. Database Approach
In this section, we'll implement multi-tenancy based on a Database per Tenant model.
5.1. Tenants Declaration
In this approach, we have multiple databases, so we need to declare multiple data sources in the Spring Boot application.
We can configure the DataSources in separate tenant files. So, we create the tenant_1.properties file in allTenants directory and declare the tenant's data source:
Moreover, we create a tenant_2.properties file for another tenant:
We will end up with a file for each tenant:
5.2. DataSource Declaration
Now we need to read the tenant's data and create DataSource using the DataSourceBuilder class. Also, we set DataSources in the AbstractRoutingDataSource class.
Let's add a MultitenantConfiguration class for that:
First, we read the tenants' definitions from allTenants directory and create the DataSource bean using DataSourceBuilder class. After that, we need to set a default data source and target source for MultitenantDataSource class to connect to using setDefaultTargetDataSource and setTargetDataSources, respectively. We set one of the tenant's names as a default data source from the application.properties file using defaultTenant attribute. To finalize the initialization of the data source, we call the afterPropertiesSet() method.
Now that our setup is ready.
6. Test
6.1. Creating Database for Tenants
First, we need to define two databases in PostgreSQL:
After that, we create an employee table in each database using the below script:
6.2. Sample Controller
Let's create an EmployeeController class for creating and saving the Employee entity in the specified tenant in the request header:
6.3. Sample Request
Let's create a post request for inserting an employee entity in tenant ID tenant_1 using Postman:
Moreover, we send a request to tenant_2:
After that, when we check the database, we see that each request has been saved in the related tenant's database.
7. Security
Multi-tenancy should protect customers' data within a shared environment. This means each tenant can only access their data. Therefore, we need to add security to our tenants. Let's build a system where the user has to log into the application and get a JWT, which is then used to prove the right to access the tenancy.
7.1. Maven Dependencies
Let's start by adding the spring-boot-starter-security dependency in the pom.xml:
Also, we need to generate and verify the JWT. To do that, we add the jjwt to our pom.xml:
7.2. Security Configuration
First, we need to provide the authentication capability for the tenant's user. For simplicity, let's use the in-memory user declaration in SecurityConfiguration class:
We add two users for two tenants. Moreover, we consider the tenant as a role. According to the above code, username user and admin have access to tenant_1 and tenant_2, respectively.
Now, we create a filter for the authentication of users. Let's add the LoginFilter class:
The LoginFilter class extends AbstractAuthenticationProcessingFilter. The AbstractAuthenticationProcessingFilter intercepts a request and attempts to perform authentication using attemptAuthentication() method. In this method, we map the user credentials to the AccountCredentials DTO class and authenticate the user against the in-memory authentication manager:
7.3. JWT
Now we need to generate the JWT and add the tenant ID. In order to do that, we override successfulAuthentication() method. This method executes after successful authentication:
According to the above code, we get the user's role and add it JWT. To do that, we create AuthenticationService class and addToken() method:
The addToken method generated the JWT that contains tenant ID as an audience claim and added it to the Authorization header in the response.
Finally, we add the LoginFilter in SecurityConfiguration class:
Moreover, we add the AuthenticationFilter class for setting the Authentication in SecurityContextHolder class:
7.4. Getting Tenant ID from JWT
Let's modify the TenantFilter for setting the current tenant in TenantContext:
In this situation, we get the tenant ID from the JWT using the getTenant() method from AuthenticationService class:
8. Security Test
8.1. JWT Generation
Let's generate the JWT for the username user. To do that, we post the credential to /login endpoints:
Let's check the token:
When we decode the token, we find out the tenant ID sets as the audience claim:
8.2. Sample Request
Let's create a post request for inserting an employee entity using the generated token:
We set the generated token in the Authorization header. The tenant ID has been extracted from the token and set in the TenantContext.
9. Conclusion
In this article, we looked at different multi-tenancy models.
We described the required class for adding multi-tenancy in the Spring Boot application using Spring Data JPA for Separate Database and Shared Database and Separate Schema models.
Then, we set up the required environment for testing the multi-tenancy in the PostgreSQL database.
Finally, we added security to the tenants using JWT.
As always, the full source code of this tutorial is available over on GitHub.
No comments:
Post a Comment