├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── example │ │ ├── MultitenancyMySqlApplication.java │ │ ├── model │ │ ├── CustomUserDetails.java │ │ ├── Employee.java │ │ ├── Role.java │ │ └── User.java │ │ ├── multitenancy │ │ ├── CurrentTenantIdentifierResolverImpl.java │ │ ├── DataSourceBasedMultiTenantConnectionProviderImpl.java │ │ ├── MultiTenancyJpaConfiguration.java │ │ └── MultitenancyProperties.java │ │ ├── repository │ │ ├── RoleRepository.java │ │ └── UserRepository.java │ │ ├── security │ │ ├── CustomAuthenticationFilter.java │ │ ├── CustomAuthenticationToken.java │ │ ├── CustomSecurityConfig.java │ │ ├── CustomUserDetailsAuthenticationProvider.java │ │ ├── CustomUserDetailsService.java │ │ └── CustomUserDetailsServiceImpl.java │ │ ├── service │ │ ├── RoleService.java │ │ ├── RoleServiceImpl.java │ │ ├── UserService.java │ │ └── UserServiceImpl.java │ │ ├── util │ │ └── TenantContextHolder.java │ │ └── web │ │ └── LoginController.java └── resources │ ├── application.yml │ ├── static │ └── css │ │ └── main.css │ └── templates │ ├── index.html │ ├── login.html │ └── user │ └── index.html └── test └── java └── com └── example └── MultitenancyMySqlApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | nbproject/private/ 21 | build/ 22 | nbbuild/ 23 | dist/ 24 | nbdist/ 25 | .nb-gradle/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Saas style database per tenant multitenancy with Spring Boot 2 and Spring Security 5 2 | SaaS application style multi-tenancy with database per tenant using Spring Boot 2 + JPA + Hibernate + Spring Security 5. This app 3 | is built with MySQL as the database. It can be adapted to use any other database like Microsoft SQL Server. 4 | 5 | This repository contains code which accompanies the blog post [Building SaaS style multi-tenant web app with Spring Boot 2 and Spring Security 5](https://sunitkatkar.blogspot.com/2018/04/building-saas-style-multi-tenant-web2.html) 6 | 7 | ## Getting Started 8 | 9 | This is a typical maven project. Download the source as a zip file or checkout the code 10 | and import as an Existing Maven project in your IDE. 11 | 12 | ### Prerequisites 13 | 14 | * Java 8 15 | * Spring Boot 2 16 | * MySQL 17 | * Not mandatory, but you can use any suitable IDE like Spring STS 18 | 19 | 20 | ## Authors 21 | 22 | * **Sunit Katkar** - *Initial work* - [Sunit Katkar](https://sunitkatkar.blogspot.com/) 23 | 24 | 25 | 26 | ## License 27 | 28 | This project is licensed under the Apache License - see the [LICENSE.md](LICENSE.md) file for details 29 | 30 | ## Request 31 | You are free to fork this repository, but please drop me a note at sunitkatkar@gmail.com 32 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | com.example 7 | multitenancy-mysql 8 | 1.0.1 9 | jar 10 | multitenancy-mysql 11 | Spring Boot JPA Hibernate with Per Database Multi-Tenancy with Spring Security 12 | 13 | 14 | Sunit Katkar 15 | sunitkatkar@gmail.com 16 | https://sunitkatkar.blogspot.com/ 17 | 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-parent 23 | 2.0.1.RELEASE 24 | 25 | 26 | 27 | 28 | UTF-8 29 | UTF-8 30 | 1.8 31 | 32 | 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-data-jpa 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-security 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-thymeleaf 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-web 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-configuration-processor 53 | true 54 | 55 | 56 | mysql 57 | mysql-connector-java 58 | runtime 59 | 60 | 61 | org.springframework.boot 62 | spring-boot-starter-test 63 | test 64 | 65 | 66 | org.springframework.security 67 | spring-security-test 68 | test 69 | 70 | 71 | net.sourceforge.nekohtml 72 | nekohtml 73 | 1.9.21 74 | 75 | 76 | 77 | org.apache.commons 78 | commons-lang3 79 | 3.7 80 | 81 | 82 | 83 | 84 | 85 | 86 | org.springframework.boot 87 | spring-boot-maven-plugin 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /src/main/java/com/example/MultitenancyMySqlApplication.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example; 17 | 18 | import org.springframework.boot.SpringApplication; 19 | import org.springframework.boot.autoconfigure.SpringBootApplication; 20 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 21 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 22 | 23 | /** 24 | * @author Sunit Katkar 25 | * @version 1.0 26 | * @since 1.0 (April 2018) 27 | */ 28 | @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) 29 | @EnableJpaRepositories("com.example.repository") 30 | public class MultitenancyMySqlApplication { 31 | 32 | public static void main(String[] args) { 33 | SpringApplication.run(MultitenancyMySqlApplication.class, args); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/CustomUserDetails.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.model; 17 | 18 | import java.util.Collection; 19 | 20 | import org.springframework.security.core.GrantedAuthority; 21 | 22 | /** 23 | * CustomUserDetails class extends the Spring Security provided 24 | * {@link org.springframework.security.core.userdetails.User} class for 25 | * authentication purpose. Do not confuse this with the {@link User} class which 26 | * is an entity for storing application specific user details like username, 27 | * password, tenant, etc in the database using the JPA {@literal @}Entity 28 | * annotation. 29 | * 30 | * @author Sunit Katkar 31 | * @version 1.0 32 | * @since 1.0 (April 2018) 33 | * 34 | */ 35 | public class CustomUserDetails extends org.springframework.security.core.userdetails.User { 36 | 37 | private static final long serialVersionUID = 1L; 38 | 39 | /** 40 | * The extra field in the login form is for the tenant name 41 | */ 42 | private String tenant; 43 | 44 | /** 45 | * Constructor based on the spring security User class but with an extra 46 | * argument tenant to store the tenant name submitted by the end 47 | * user. 48 | * 49 | * @param username 50 | * @param password 51 | * @param authorities 52 | * @param tenant 53 | */ 54 | public CustomUserDetails(String username, String password, Collection authorities, 55 | String tenant) { 56 | super(username, password, authorities); 57 | this.tenant = tenant; 58 | } 59 | 60 | // Getters and Setters 61 | public String getTenant() { 62 | return tenant; 63 | } 64 | 65 | public void setTenant(String tenant) { 66 | this.tenant = tenant; 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/Employee.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.model; 18 | 19 | import javax.persistence.Column; 20 | import javax.persistence.Entity; 21 | import javax.persistence.GeneratedValue; 22 | import javax.persistence.GenerationType; 23 | import javax.persistence.Id; 24 | import javax.persistence.Table; 25 | 26 | /** 27 | * Just a regular entity which will be stored in all tenant databases. 28 | * 29 | * @author Sunit Katkar 30 | * @version 1.0 31 | * @since 1.0 (April 2018) 32 | */ 33 | @Entity 34 | @Table(name = "employee") 35 | public class Employee { 36 | 37 | @Id 38 | @GeneratedValue(strategy = GenerationType.AUTO) 39 | @Column(name = "id", nullable = false, unique = true) 40 | private Long id; 41 | 42 | @Column(name = "first_name") 43 | private String firstName; 44 | 45 | @Column(name = "last_name") 46 | private String lastName; 47 | 48 | @Column(name = "department") 49 | private String department; 50 | 51 | private String office; 52 | 53 | public Long getId() { 54 | return id; 55 | } 56 | 57 | public void setId(Long id) { 58 | this.id = id; 59 | } 60 | 61 | public String getFirstName() { 62 | return firstName; 63 | } 64 | 65 | public void setFirstName(String firstName) { 66 | this.firstName = firstName; 67 | } 68 | 69 | public String getLastName() { 70 | return lastName; 71 | } 72 | 73 | public void setLastName(String lastName) { 74 | this.lastName = lastName; 75 | } 76 | 77 | public String getDepartment() { 78 | return department; 79 | } 80 | 81 | public void setDepartment(String department) { 82 | this.department = department; 83 | } 84 | 85 | public String getOffice() { 86 | return office; 87 | } 88 | 89 | public void setOffice(String office) { 90 | this.office = office; 91 | } 92 | 93 | @Override 94 | public int hashCode() { 95 | final int prime = 31; 96 | int result = 1; 97 | result = prime * result + ((department == null) ? 0 : department.hashCode()); 98 | result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); 99 | result = prime * result + ((id == null) ? 0 : id.hashCode()); 100 | result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); 101 | result = prime * result + ((office == null) ? 0 : office.hashCode()); 102 | return result; 103 | } 104 | 105 | @Override 106 | public boolean equals(Object obj) { 107 | if (this == obj) 108 | return true; 109 | if (obj == null) 110 | return false; 111 | if (getClass() != obj.getClass()) 112 | return false; 113 | Employee other = (Employee) obj; 114 | if (department == null) { 115 | if (other.department != null) 116 | return false; 117 | } else if (!department.equals(other.department)) 118 | return false; 119 | if (firstName == null) { 120 | if (other.firstName != null) 121 | return false; 122 | } else if (!firstName.equals(other.firstName)) 123 | return false; 124 | if (id == null) { 125 | if (other.id != null) 126 | return false; 127 | } else if (!id.equals(other.id)) 128 | return false; 129 | if (lastName == null) { 130 | if (other.lastName != null) 131 | return false; 132 | } else if (!lastName.equals(other.lastName)) 133 | return false; 134 | if (office == null) { 135 | if (other.office != null) 136 | return false; 137 | } else if (!office.equals(other.office)) 138 | return false; 139 | return true; 140 | } 141 | 142 | /* 143 | * (non-Javadoc) 144 | * 145 | * @see java.lang.Object#toString() 146 | */ 147 | @Override 148 | public String toString() { 149 | StringBuilder builder = new StringBuilder(); 150 | builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=") 151 | .append(lastName).append(", department=").append(department).append(", office=").append(office) 152 | .append("]"); 153 | return builder.toString(); 154 | } 155 | 156 | } 157 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/Role.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.model; 18 | 19 | import java.io.Serializable; 20 | import java.util.Set; 21 | 22 | import javax.persistence.Column; 23 | import javax.persistence.Entity; 24 | import javax.persistence.FetchType; 25 | import javax.persistence.GeneratedValue; 26 | import javax.persistence.GenerationType; 27 | import javax.persistence.Id; 28 | import javax.persistence.ManyToMany; 29 | import javax.persistence.Table; 30 | 31 | /** 32 | * Role entity to represent a ROLE of the {@link User} in the system. 33 | * 34 | * The JPA definitions of {@link User} and {@link Role} will cause the following 35 | * 3 tables to be created: 36 | * 41 | * 42 | * @author Sunit Katkar 43 | * @version 1.0 44 | * @since 1.0 (April 2018) 45 | * 46 | */ 47 | @Entity 48 | @Table(name = "role") 49 | public class Role implements Serializable { 50 | 51 | private static final long serialVersionUID = 1L; 52 | 53 | @Id 54 | @GeneratedValue(strategy = GenerationType.AUTO) 55 | @Column(name = "role_id") 56 | private int id; 57 | 58 | @Column(name = "role") 59 | private String role; 60 | 61 | /** 62 | * Defining the Many-to-Many relation of users and roles. A Role can belong to 63 | * many Users and many Users can belong to a Role. 64 | */ 65 | @ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY) 66 | private Set users; 67 | 68 | // Getters and setters 69 | 70 | public int getId() { 71 | return id; 72 | } 73 | 74 | public void setId(int id) { 75 | this.id = id; 76 | } 77 | 78 | public String getRole() { 79 | return role; 80 | } 81 | 82 | public void setRole(String role) { 83 | this.role = role; 84 | } 85 | 86 | /** 87 | * @return the users 88 | */ 89 | public Set getUsers() { 90 | return users; 91 | } 92 | 93 | /** 94 | * @param users 95 | * the users to set 96 | */ 97 | public void setUsers(Set users) { 98 | this.users = users; 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/User.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.model; 18 | 19 | import java.io.Serializable; 20 | import java.util.Set; 21 | 22 | import javax.persistence.CascadeType; 23 | import javax.persistence.Column; 24 | import javax.persistence.Entity; 25 | import javax.persistence.FetchType; 26 | import javax.persistence.GeneratedValue; 27 | import javax.persistence.GenerationType; 28 | import javax.persistence.Id; 29 | import javax.persistence.JoinColumn; 30 | import javax.persistence.JoinTable; 31 | import javax.persistence.ManyToMany; 32 | import javax.persistence.Table; 33 | import javax.validation.constraints.NotNull; 34 | 35 | import org.hibernate.validator.constraints.Length; 36 | 37 | /** 38 | * User entity to represent a {@link User} of the system. 39 | * 40 | * The JPA definitions of {@link User} and {@link Role} will cause the following 41 | * 3 tables to be created: 42 | *
    43 | *
  • user
  • 44 | *
  • role
  • 45 | *
  • user_roles
  • 46 | *
47 | * 48 | * @author Sunit Katkar 49 | * @version 1.0 50 | * @since 1.0 (April 2018) 51 | */ 52 | @Entity 53 | @Table(name = "user") 54 | public class User implements Serializable { 55 | 56 | private static final long serialVersionUID = 1L; 57 | 58 | @Id 59 | @GeneratedValue(strategy = GenerationType.AUTO) 60 | @Column(name = "user_id") 61 | private int id; 62 | 63 | @Column(name = "username") 64 | @NotNull(message = "*Please provide your username") 65 | private String username; 66 | 67 | @Column(name = "password") 68 | @Length(min = 5, message = "*Your password must have at least 5 characters") 69 | @NotNull(message = "*Please provide your password") 70 | private String password; 71 | 72 | /** 73 | * Boolean flag to set if the user should be active when created in the User 74 | * table 75 | */ 76 | @Column(name = "active") 77 | private boolean active; 78 | 79 | /** 80 | * Name of the tenant to which the user belongs 81 | */ 82 | @Column(name = "tenant") 83 | private String tenant; 84 | 85 | /** 86 | * Many-to-Many relation between a User and Role. A user can have many roles and 87 | * vice versa 88 | */ 89 | @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) 90 | @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) 91 | private Set roles; 92 | 93 | // Getters and setters 94 | 95 | public int getId() { 96 | return id; 97 | } 98 | 99 | public void setId(int id) { 100 | this.id = id; 101 | } 102 | 103 | public String getUsername() { 104 | return username; 105 | } 106 | 107 | public void setUsername(String username) { 108 | this.username = username; 109 | } 110 | 111 | public String getPassword() { 112 | return password; 113 | } 114 | 115 | public void setPassword(String password) { 116 | this.password = password; 117 | } 118 | 119 | public boolean isActive() { 120 | return active; 121 | } 122 | 123 | public void setActive(boolean active) { 124 | this.active = active; 125 | } 126 | 127 | public String getTenant() { 128 | return tenant; 129 | } 130 | 131 | public void setTenant(String tenant) { 132 | this.tenant = tenant; 133 | } 134 | 135 | public Set getRoles() { 136 | return roles; 137 | } 138 | 139 | public void setRoles(Set roles) { 140 | this.roles = roles; 141 | } 142 | 143 | } 144 | -------------------------------------------------------------------------------- /src/main/java/com/example/multitenancy/CurrentTenantIdentifierResolverImpl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.multitenancy; 18 | 19 | import org.apache.commons.lang3.StringUtils; 20 | import org.hibernate.context.spi.CurrentTenantIdentifierResolver; 21 | import org.springframework.stereotype.Component; 22 | 23 | import com.example.util.TenantContextHolder; 24 | 25 | /** 26 | * Hibernate needs to know which database to use i.e. which tenant to connect 27 | * to. This class provides a mechanism to provide the correct datasource at run 28 | * time. 29 | * 30 | * @see {@link com.example.util.TenantContextHolder} 31 | * @see {@link com.example.security.CustomAuthenticationFilter} 32 | * 33 | * @author Sunit Katkar 34 | * @version 1.0 35 | * @since 1.0 (April 2018) 36 | */ 37 | @Component 38 | public class CurrentTenantIdentifierResolverImpl implements CurrentTenantIdentifierResolver { 39 | 40 | private static final String DEFAULT_TENANT_ID = "tenant_1"; 41 | 42 | /* 43 | * (non-Javadoc) 44 | * 45 | * @see org.hibernate.context.spi.CurrentTenantIdentifierResolver# 46 | * resolveCurrentTenantIdentifier() 47 | */ 48 | @Override 49 | public String resolveCurrentTenantIdentifier() { 50 | // The tenant is stored in a ThreadLocal before the end user's login information 51 | // is submitted for spring security authentication mechanism. Refer to 52 | // CustomAuthenticationFilter 53 | String tenant = TenantContextHolder.getTenant(); 54 | return StringUtils.isNotBlank(tenant) ? tenant : DEFAULT_TENANT_ID; 55 | } 56 | 57 | /* 58 | * (non-Javadoc) 59 | * 60 | * @see org.hibernate.context.spi.CurrentTenantIdentifierResolver# 61 | * validateExistingCurrentSessions() 62 | */ 63 | @Override 64 | public boolean validateExistingCurrentSessions() { 65 | return true; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/example/multitenancy/DataSourceBasedMultiTenantConnectionProviderImpl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.multitenancy; 18 | 19 | import java.util.Map; 20 | 21 | import javax.sql.DataSource; 22 | 23 | import org.hibernate.engine.jdbc.connections.spi.AbstractDataSourceBasedMultiTenantConnectionProviderImpl; 24 | import org.springframework.beans.factory.annotation.Autowired; 25 | import org.springframework.stereotype.Component; 26 | 27 | /** 28 | * This class does the job of selecting the correct database based on the tenant 29 | * id found by the {@link CurrentTenantIdentifierResolverImpl} 30 | * 31 | * @author Sunit Katkar 32 | * @version 1.0 33 | * @since 1.0 (April 2018) 34 | */ 35 | @Component 36 | public class DataSourceBasedMultiTenantConnectionProviderImpl 37 | extends AbstractDataSourceBasedMultiTenantConnectionProviderImpl { 38 | 39 | private static final long serialVersionUID = 1L; 40 | 41 | @Autowired 42 | private Map dataSourcesMtApp; 43 | 44 | /* 45 | * (non-Javadoc) 46 | * 47 | * @see org.hibernate.engine.jdbc.connections.spi. 48 | * AbstractDataSourceBasedMultiTenantConnectionProviderImpl#selectAnyDataSource( 49 | * ) 50 | */ 51 | @Override 52 | protected DataSource selectAnyDataSource() { 53 | return this.dataSourcesMtApp.values().iterator().next(); 54 | } 55 | 56 | /* 57 | * (non-Javadoc) 58 | * 59 | * @see org.hibernate.engine.jdbc.connections.spi. 60 | * AbstractDataSourceBasedMultiTenantConnectionProviderImpl#selectDataSource( 61 | * java.lang.String) 62 | */ 63 | @Override 64 | protected DataSource selectDataSource(String tenantIdentifier) { 65 | return this.dataSourcesMtApp.get(tenantIdentifier); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/example/multitenancy/MultiTenancyJpaConfiguration.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.multitenancy; 18 | 19 | import java.util.HashMap; 20 | import java.util.LinkedHashMap; 21 | import java.util.Map; 22 | 23 | import javax.persistence.EntityManagerFactory; 24 | import javax.sql.DataSource; 25 | 26 | import org.hibernate.MultiTenancyStrategy; 27 | import org.hibernate.cfg.Environment; 28 | import org.hibernate.context.spi.CurrentTenantIdentifierResolver; 29 | import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider; 30 | import org.springframework.beans.factory.annotation.Autowired; 31 | import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; 32 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 33 | import org.springframework.boot.jdbc.DataSourceBuilder; 34 | import org.springframework.context.annotation.Bean; 35 | import org.springframework.context.annotation.Configuration; 36 | import org.springframework.context.annotation.Primary; 37 | import org.springframework.orm.jpa.JpaTransactionManager; 38 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 39 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; 40 | import org.springframework.transaction.PlatformTransactionManager; 41 | import org.springframework.transaction.annotation.EnableTransactionManagement; 42 | 43 | import com.example.model.Employee; 44 | import com.example.multitenancy.MultitenancyProperties.DataSourceProperties; 45 | 46 | /** 47 | * This class defines the data sources to be used for accessing the different 48 | * databases (one database per tenant). It generates the Hibernate session and 49 | * entity bean for database access via Spring JPA as well as the Transaction 50 | * manager to be used. 51 | * 52 | * @author Sunit Katkar 53 | * @version 1.0 54 | * @since 1.0 (April 2018) 55 | */ 56 | @Configuration 57 | @EnableConfigurationProperties({ MultitenancyProperties.class, JpaProperties.class }) 58 | @EnableTransactionManagement 59 | public class MultiTenancyJpaConfiguration { 60 | 61 | @Autowired 62 | private JpaProperties jpaProperties; 63 | 64 | @Autowired 65 | private MultitenancyProperties multitenancyProperties; 66 | 67 | /** 68 | * Builds a map of all data sources defined in the application.yml file 69 | * 70 | * @return 71 | */ 72 | @Primary 73 | @Bean(name = "dataSourcesMtApp") 74 | public Map dataSourcesMtApp() { 75 | Map result = new HashMap<>(); 76 | for (DataSourceProperties dsProperties : this.multitenancyProperties.getDataSources()) { 77 | 78 | DataSourceBuilder factory = DataSourceBuilder.create().url(dsProperties.getUrl()) 79 | .username(dsProperties.getUsername()).password(dsProperties.getPassword()) 80 | .driverClassName(dsProperties.getDriverClassName()); 81 | 82 | result.put(dsProperties.getTenantId(), factory.build()); 83 | } 84 | return result; 85 | } 86 | 87 | /** 88 | * Autowires the data sources so that they can be used by the Spring JPA to 89 | * access the database 90 | * 91 | * @return 92 | */ 93 | @Bean 94 | public MultiTenantConnectionProvider multiTenantConnectionProvider() { 95 | // Autowires dataSourcesMtApp 96 | return new DataSourceBasedMultiTenantConnectionProviderImpl(); 97 | } 98 | 99 | /** 100 | * Since this is a multi-tenant application, Hibernate requires that the current 101 | * tenant identifier is resolved for use with 102 | * {@link org.hibernate.context.spi.CurrentSessionContext} and 103 | * {@link org.hibernate.SessionFactory#getCurrentSession()} 104 | * 105 | * @return 106 | */ 107 | @Bean 108 | public CurrentTenantIdentifierResolver currentTenantIdentifierResolver() { 109 | return new CurrentTenantIdentifierResolverImpl(); 110 | } 111 | 112 | /** 113 | * org.springframework.beans.factory.FactoryBean that creates a JPA 114 | * {@link javax.persistence.EntityManagerFactory} according to JPA's standard 115 | * container bootstrap contract. This is the most powerful way to set up a 116 | * shared JPA EntityManagerFactory in a Spring application context; the 117 | * EntityManagerFactory can then be passed to JPA-based DAOs via dependency 118 | * injection. Note that switching to a JNDI lookup or to a 119 | * {@link org.springframework.orm.jpa.LocalEntityManagerFactoryBean} definition 120 | * is just a matter of configuration! 121 | * 122 | * @param multiTenantConnectionProvider 123 | * @param currentTenantIdentifierResolver 124 | * @return 125 | */ 126 | @Bean 127 | public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean( 128 | MultiTenantConnectionProvider multiTenantConnectionProvider, 129 | CurrentTenantIdentifierResolver currentTenantIdentifierResolver) { 130 | 131 | Map hibernateProps = new LinkedHashMap<>(); 132 | hibernateProps.putAll(this.jpaProperties.getProperties()); 133 | hibernateProps.put(Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE); 134 | hibernateProps.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider); 135 | hibernateProps.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver); 136 | 137 | // No dataSource is set to resulting entityManagerFactoryBean 138 | LocalContainerEntityManagerFactoryBean result = new LocalContainerEntityManagerFactoryBean(); 139 | result.setPackagesToScan(new String[] { Employee.class.getPackage().getName() }); 140 | result.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); 141 | result.setJpaPropertyMap(hibernateProps); 142 | 143 | return result; 144 | } 145 | 146 | /** 147 | * Interface used to interact with the entity manager factory for the 148 | * persistence unit. 149 | * 150 | * @param entityManagerFactoryBean 151 | * @return 152 | */ 153 | @Bean 154 | public EntityManagerFactory entityManagerFactory(LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) { 155 | return entityManagerFactoryBean.getObject(); 156 | } 157 | 158 | /** 159 | * Creates a new 160 | * {@link org.springframework.orm.jpa.JpaTransactionManager#JpaTransactionManager(EntityManagerFactory emf)} 161 | * instance. 162 | * 163 | * {@link org.springframework.transaction.PlatformTransactionManager} is the 164 | * central interface in Spring's transaction infrastructure. Applications can 165 | * use this directly, but it is not primarily meant as API: Typically, 166 | * applications will work with either TransactionTemplate or declarative 167 | * transaction demarcation through AOP. 168 | * 169 | * @param entityManagerFactory 170 | * @return 171 | */ 172 | @Bean 173 | public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { 174 | return new JpaTransactionManager(entityManagerFactory); 175 | } 176 | } -------------------------------------------------------------------------------- /src/main/java/com/example/multitenancy/MultitenancyProperties.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.multitenancy; 18 | 19 | import java.util.List; 20 | 21 | import org.springframework.boot.context.properties.ConfigurationProperties; 22 | import org.springframework.context.annotation.Configuration; 23 | 24 | /** 25 | * This class reads the multitenancy.mtapp node from 26 | * application.yml file and populates a list of 27 | * {@link org.springframework.boot.autoconfigure.jdbc.DataSourceProperties} 28 | * objects, with each instance containing the data source details about the 29 | * database like url, username, password etc 30 | * 31 | * @author Sunit Katkar 32 | * @version 1.0 33 | * @since 1.0 (April 2018) 34 | */ 35 | @Configuration 36 | @ConfigurationProperties("multitenancy.mtapp") 37 | public class MultitenancyProperties { 38 | 39 | private List dataSourcesProps; 40 | 41 | public List getDataSources() { 42 | return this.dataSourcesProps; 43 | } 44 | 45 | public void setDataSources(List dataSourcesProps) { 46 | this.dataSourcesProps = dataSourcesProps; 47 | } 48 | 49 | public static class DataSourceProperties extends org.springframework.boot.autoconfigure.jdbc.DataSourceProperties { 50 | 51 | private String tenantId; 52 | 53 | public String getTenantId() { 54 | return tenantId; 55 | } 56 | 57 | public void setTenantId(String tenantId) { 58 | this.tenantId = tenantId; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/example/repository/RoleRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.repository; 18 | 19 | import org.springframework.data.jpa.repository.JpaRepository; 20 | import org.springframework.stereotype.Repository; 21 | 22 | import com.example.model.Role; 23 | 24 | /** 25 | * Repository for the {@link Role} JPA entity. Any custom methods, not already 26 | * defined in {@link JpaRepository}, are to be defined here. 27 | * 28 | * @author Sunit Katkar 29 | * @version 1.0 30 | * @since 1.0 (April 2018) 31 | */ 32 | @Repository 33 | public interface RoleRepository extends JpaRepository { 34 | 35 | /** 36 | * Query to find a Role entiry based on the {@link Role} name 37 | * 38 | * @param role 39 | * @return 40 | */ 41 | Role findByRole(String role); 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/example/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.repository; 18 | 19 | import org.springframework.data.jpa.repository.JpaRepository; 20 | import org.springframework.data.jpa.repository.Query; 21 | import org.springframework.data.repository.query.Param; 22 | import org.springframework.stereotype.Repository; 23 | 24 | import com.example.model.User; 25 | 26 | /** 27 | * Repository for the {@link User} JPA entity. Any custom methods, not already 28 | * defined in {@link JpaRepository}, are to be defined here 29 | * 30 | * @author Sunit Katkar 31 | * @version 1.0 32 | * @since 1.0 (April 2018) 33 | */ 34 | @Repository 35 | public interface UserRepository extends JpaRepository { 36 | 37 | /** 38 | * Custom / Named query for selecting a user based on the username and tenant id 39 | * 40 | * @param username 41 | * @param tenant 42 | * @return 43 | */ 44 | @Query("select p from User p where p.username = :username and p.tenant = :tenant") 45 | User findByUsernameAndTenantname(@Param("username") String username, @Param("tenant") String tenant); 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/example/security/CustomAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.security; 17 | 18 | import javax.servlet.http.HttpServletRequest; 19 | import javax.servlet.http.HttpServletResponse; 20 | 21 | import org.springframework.security.authentication.AuthenticationServiceException; 22 | import org.springframework.security.core.Authentication; 23 | import org.springframework.security.core.AuthenticationException; 24 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 25 | 26 | import com.example.util.TenantContextHolder; 27 | 28 | /** 29 | * This is the filter which is called first when the user submits the login 30 | * form. This filter extracts the username, password, and tenant fields from the 31 | * request. These values are used to create an instance of 32 | * {@link CustomAuthenticationToken} which is passed to the 33 | * {@link AuthenticationProvider} for authentication: 34 | * 35 | * @author Sunit Katkar 36 | * @version 1.0 37 | * @since 1.0 (April 2018) 38 | * 39 | */ 40 | public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter { 41 | 42 | public static final String SPRING_SECURITY_FORM_TENANT_NAME_KEY = "tenant"; 43 | 44 | /* 45 | * (non-Javadoc) 46 | * 47 | * @see org.springframework.security.web.authentication. 48 | * UsernamePasswordAuthenticationFilter#attemptAuthentication(javax.servlet.http 49 | * .HttpServletRequest, javax.servlet.http.HttpServletResponse) 50 | */ 51 | @Override 52 | public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) 53 | throws AuthenticationException { 54 | if (!request.getMethod().equals("POST")) { 55 | throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); 56 | } 57 | 58 | CustomAuthenticationToken authRequest = getAuthRequest(request); 59 | 60 | // put in tenant context threadlocal 61 | String tenant = authRequest.getTenant(); 62 | TenantContextHolder.setTenantId(tenant); 63 | 64 | setDetails(request, authRequest); 65 | 66 | return this.getAuthenticationManager().authenticate(authRequest); 67 | } 68 | 69 | /** 70 | * @param request 71 | * @return 72 | */ 73 | private CustomAuthenticationToken getAuthRequest(HttpServletRequest request) { 74 | String username = obtainUsername(request); 75 | String password = obtainPassword(request); 76 | String tenant = obtainTenant(request); 77 | 78 | if (username == null) { 79 | username = ""; 80 | } 81 | if (password == null) { 82 | password = ""; 83 | } 84 | if (tenant == null) { 85 | tenant = ""; 86 | } 87 | 88 | return new CustomAuthenticationToken(username, password, tenant); 89 | } 90 | 91 | /** 92 | * @param request 93 | * @return 94 | */ 95 | private String obtainTenant(HttpServletRequest request) { 96 | return request.getParameter(SPRING_SECURITY_FORM_TENANT_NAME_KEY); 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/com/example/security/CustomAuthenticationToken.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.security; 18 | 19 | import java.util.Collection; 20 | 21 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 22 | import org.springframework.security.core.GrantedAuthority; 23 | 24 | /** 25 | * {@link CustomAuthenticationToken} is provided to the 26 | * {@link AuthenticationProvider} so that the user can be authenticated. This 27 | * token is enhanced by including the additional tenant field 28 | * extracted by the {@link CustomAuthenticationFilter} from the user submitted 29 | * login form. 30 | * 31 | * @author Sunit Katkar 32 | * @version 1.0 33 | * @since 1.0 (April 2018) 34 | */ 35 | public class CustomAuthenticationToken extends UsernamePasswordAuthenticationToken { 36 | 37 | private static final long serialVersionUID = 1L; 38 | 39 | /** 40 | * The tenant i.e. database identifier 41 | */ 42 | private String tenant; 43 | 44 | /** 45 | * @param principal 46 | * @param credentials 47 | * @param tenant 48 | */ 49 | public CustomAuthenticationToken(Object principal, Object credentials, String tenant) { 50 | super(principal, credentials); 51 | this.tenant = tenant; 52 | super.setAuthenticated(false); 53 | } 54 | 55 | /** 56 | * @param principal 57 | * @param credentials 58 | * @param tenant 59 | * @param authorities 60 | */ 61 | public CustomAuthenticationToken(Object principal, Object credentials, String tenant, 62 | Collection authorities) { 63 | super(principal, credentials, authorities); 64 | this.tenant = tenant; 65 | super.setAuthenticated(true); // must use super, as we override 66 | } 67 | 68 | public String getTenant() { 69 | return this.tenant; 70 | } 71 | } -------------------------------------------------------------------------------- /src/main/java/com/example/security/CustomSecurityConfig.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.security; 18 | 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.context.annotation.Bean; 21 | import org.springframework.context.annotation.Configuration; 22 | import org.springframework.security.authentication.AuthenticationProvider; 23 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 24 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 25 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 26 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 27 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 28 | import org.springframework.security.crypto.password.PasswordEncoder; 29 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; 30 | import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; 31 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 32 | 33 | /** 34 | * Configuration of security related beans and methods. The access to different 35 | * urls within the application is defined here. 36 | * 37 | * @author Sunit Katkar 38 | * @version 1.0 39 | * @since 1.0 (April 2018) 40 | * 41 | */ 42 | @Configuration 43 | @EnableWebSecurity 44 | public class CustomSecurityConfig extends WebSecurityConfigurerAdapter { 45 | 46 | @Autowired 47 | private CustomUserDetailsService userDetailsService; 48 | 49 | /** 50 | * This is where access to various resources (urls) in the application is 51 | * defined 52 | */ 53 | @Override 54 | protected void configure(HttpSecurity http) throws Exception { 55 | //@formatter:off 56 | http 57 | .addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class) 58 | .authorizeRequests() 59 | .antMatchers("/css/**", "/index").permitAll() 60 | .antMatchers("/user/**").authenticated() 61 | .and() 62 | .formLogin().loginPage("/login") 63 | .and() 64 | .logout() 65 | .logoutUrl("/logout"); 66 | //@formatter:on 67 | } 68 | 69 | /** 70 | * Create an instance of the custom authentication filter which intercepts and 71 | * processes the end user's login form submission for further authentication 72 | * processing. This filter is added before other filters so that it can 73 | * intercept the user login form submission and extract the the additional 74 | * 'tenant' field 75 | * 76 | * @return 77 | * @throws Exception 78 | */ 79 | public CustomAuthenticationFilter authenticationFilter() throws Exception { 80 | CustomAuthenticationFilter filter = new CustomAuthenticationFilter(); 81 | filter.setAuthenticationManager(authenticationManagerBean()); 82 | filter.setAuthenticationFailureHandler(failureHandler()); 83 | filter.setAuthenticationSuccessHandler(successHandler()); 84 | return filter; 85 | } 86 | 87 | @Autowired 88 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 89 | auth.authenticationProvider(authProvider()); 90 | } 91 | 92 | /** 93 | * Authentication provider which provides the logged in user's credentials for 94 | * verification and authentication if they are coeect 95 | * 96 | * @return 97 | */ 98 | public AuthenticationProvider authProvider() { 99 | // The custom authentication provider defined for this app 100 | CustomUserDetailsAuthenticationProvider provider = new CustomUserDetailsAuthenticationProvider( 101 | passwordEncoder(), userDetailsService); 102 | return provider; 103 | } 104 | 105 | /** 106 | * The page to show if authentication fails 107 | * 108 | * @return 109 | */ 110 | public SimpleUrlAuthenticationFailureHandler failureHandler() { 111 | return new SimpleUrlAuthenticationFailureHandler("/login?error=true"); 112 | } 113 | 114 | public SimpleUrlAuthenticationSuccessHandler successHandler() { 115 | return new SimpleUrlAuthenticationSuccessHandler("/user/index"); 116 | } 117 | 118 | @Bean(name = "passwordEncoder") 119 | public PasswordEncoder passwordEncoder() { 120 | return new BCryptPasswordEncoder(); 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /src/main/java/com/example/security/CustomUserDetailsAuthenticationProvider.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.security; 18 | 19 | import org.springframework.security.authentication.BadCredentialsException; 20 | import org.springframework.security.authentication.InternalAuthenticationServiceException; 21 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 22 | import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider; 23 | import org.springframework.security.core.AuthenticationException; 24 | import org.springframework.security.core.userdetails.UserDetails; 25 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 26 | import org.springframework.security.crypto.password.PasswordEncoder; 27 | import org.springframework.util.Assert; 28 | 29 | /** 30 | * {@link CustomUserDetailsAuthenticationProvider} extends 31 | * {@link AbstractUserDetailsAuthenticationProvider} and delegates to the 32 | * {@link CustomUserDetailService} to retrieve the User. The most important 33 | * feature of this class is the implementation of the retrieveUser 34 | * method. 35 | * 36 | * Note that the authentication token must be cast to CustomAuthenticationToken 37 | * to access the custom field - tenant 38 | * 39 | * 40 | * @author Sunit Katkar 41 | * @version 1.0 42 | * @since 1.0 (April 2018) 43 | */ 44 | public class CustomUserDetailsAuthenticationProvider 45 | extends AbstractUserDetailsAuthenticationProvider { 46 | 47 | /** 48 | * The plaintext password used to perform PasswordEncoder#matches(CharSequence, 49 | * String)} on when the user is not found to avoid SEC-2056 50 | * (https://github.com/spring-projects/spring-security/issues/2280). 51 | */ 52 | private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword"; 53 | 54 | /** 55 | * For encoding and/or matching the encrypted password stored in the database 56 | * with the user submitted password 57 | */ 58 | private PasswordEncoder passwordEncoder; 59 | 60 | private CustomUserDetailsService userDetailsService; 61 | 62 | /** 63 | * The password used to perform 64 | * {@link PasswordEncoder#matches(CharSequence, String)} on when the user is not 65 | * found to avoid SEC-2056. This is necessary, because some 66 | * {@link PasswordEncoder} implementations will short circuit if the password is 67 | * not in a valid format. 68 | */ 69 | private String userNotFoundEncodedPassword; 70 | 71 | public CustomUserDetailsAuthenticationProvider(PasswordEncoder passwordEncoder, 72 | CustomUserDetailsService userDetailsService) { 73 | this.passwordEncoder = passwordEncoder; 74 | this.userDetailsService = userDetailsService; 75 | } 76 | 77 | /* 78 | * (non-Javadoc) 79 | * 80 | * @see org.springframework.security.authentication.dao. 81 | * AbstractUserDetailsAuthenticationProvider#additionalAuthenticationChecks(org. 82 | * springframework.security.core.userdetails.UserDetails, 83 | * org.springframework.security.authentication. 84 | * UsernamePasswordAuthenticationToken) 85 | */ 86 | @Override 87 | protected void additionalAuthenticationChecks(UserDetails userDetails, 88 | UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { 89 | 90 | if (authentication.getCredentials() == null) { 91 | logger.debug("Authentication failed: no credentials provided"); 92 | throw new BadCredentialsException( 93 | messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", 94 | "Bad credentials")); 95 | } 96 | // Get the password submitted by the end user 97 | String presentedPassword = authentication.getCredentials().toString(); 98 | 99 | // If the password stored in the database and the user submitted password do not 100 | // match, then signal a login error 101 | if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) { 102 | logger.debug("Authentication failed: password does not match stored value"); 103 | throw new BadCredentialsException( 104 | messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", 105 | "Bad credentials")); 106 | } 107 | } 108 | 109 | @Override 110 | protected void doAfterPropertiesSet() throws Exception { 111 | Assert.notNull(this.userDetailsService, "A UserDetailsService must be set"); 112 | this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD); 113 | } 114 | 115 | /* 116 | * (non-Javadoc) 117 | * 118 | * @see org.springframework.security.authentication.dao. 119 | * AbstractUserDetailsAuthenticationProvider#retrieveUser(java.lang.String, 120 | * org.springframework.security.authentication. 121 | * UsernamePasswordAuthenticationToken) 122 | */ 123 | @Override 124 | protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) 125 | throws AuthenticationException { 126 | CustomAuthenticationToken auth = (CustomAuthenticationToken) authentication; 127 | UserDetails loadedUser; 128 | 129 | try { 130 | loadedUser = this.userDetailsService 131 | .loadUserByUsernameAndTenantname(auth.getPrincipal().toString(), 132 | auth.getTenant()); 133 | } catch (UsernameNotFoundException notFound) { 134 | if (authentication.getCredentials() != null) { 135 | String presentedPassword = authentication.getCredentials().toString(); 136 | passwordEncoder.matches(presentedPassword, userNotFoundEncodedPassword); 137 | } 138 | throw notFound; 139 | } catch (Exception repositoryProblem) { 140 | throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), 141 | repositoryProblem); 142 | } 143 | 144 | if (loadedUser == null) { 145 | throw new InternalAuthenticationServiceException( 146 | "UserDetailsService returned null, " 147 | + "which is an interface contract violation"); 148 | } 149 | return loadedUser; 150 | } 151 | } -------------------------------------------------------------------------------- /src/main/java/com/example/security/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.security; 18 | 19 | import org.springframework.security.core.userdetails.UserDetails; 20 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 21 | 22 | /** 23 | * @author Sunit Katkar 24 | * @version 1.0 25 | * @since 1.0 (April 2018) 26 | * 27 | */ 28 | public interface CustomUserDetailsService { 29 | 30 | UserDetails loadUserByUsernameAndTenantname(String username, String tenantName) throws UsernameNotFoundException; 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/example/security/CustomUserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.security; 18 | 19 | import java.util.HashSet; 20 | import java.util.Set; 21 | 22 | import org.apache.commons.lang3.StringUtils; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.security.core.GrantedAuthority; 25 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 26 | import org.springframework.security.core.userdetails.UserDetails; 27 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 28 | import org.springframework.stereotype.Service; 29 | 30 | import com.example.model.CustomUserDetails; 31 | import com.example.model.Role; 32 | import com.example.model.User; 33 | import com.example.service.UserService; 34 | 35 | /** 36 | * {@link CustomUserDetailsService} contract defines a single method called 37 | * loadUserByUsernameAndTenantname. 38 | * 39 | * The {@link CustomUserDetailsServiceImpl} class simply implements the contract 40 | * and delegates to {@link UserService} to get the 41 | * {@link com.example.model.User} from the database so that it can be compared 42 | * with the {@link org.springframework.security.core.userdetails.User} for 43 | * authentication. Authentication occurs via the 44 | * {@link CustomUserDetailsAuthenticationProvider}. 45 | * 46 | * @author Sunit Katkar 47 | * @version 1.0 48 | * @since 1.0 (April 2018) 49 | * 50 | */ 51 | @Service("userDetailsService") 52 | public class CustomUserDetailsServiceImpl implements CustomUserDetailsService { 53 | 54 | @Autowired 55 | private UserService userService; 56 | 57 | @Override 58 | public UserDetails loadUserByUsernameAndTenantname(String username, String tenant) 59 | throws UsernameNotFoundException { 60 | if (StringUtils.isAnyBlank(username, tenant)) { 61 | throw new UsernameNotFoundException("Username and domain must be provided"); 62 | } 63 | // Look for the user based on the username and tenant by accessing the 64 | // UserRepository via the UserService 65 | User user = userService.findByUsernameAndTenantname(username, tenant); 66 | 67 | if (user == null) { 68 | throw new UsernameNotFoundException( 69 | String.format("Username not found for domain, " 70 | + "username=%s, tenant=%s", username, tenant)); 71 | } 72 | 73 | Set grantedAuthorities = new HashSet<>(); 74 | for (Role role : user.getRoles()) { 75 | grantedAuthorities.add(new SimpleGrantedAuthority(role.getRole())); 76 | } 77 | 78 | CustomUserDetails customUserDetails = 79 | new CustomUserDetails(user.getUsername(), 80 | user.getPassword(), grantedAuthorities, tenant); 81 | 82 | return customUserDetails; 83 | } 84 | } -------------------------------------------------------------------------------- /src/main/java/com/example/service/RoleService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.example.service; 5 | 6 | /** 7 | * Service definition which accesses the {@link Role} entity. This is the 8 | * recommended way to access the entities through an interface rather than using 9 | * the corresponding repository. This allows for separation into repository code 10 | * and the service layer. 11 | * 12 | * @author Sunit Katkar 13 | * @version 1.0 14 | * @since 1.0 (April 2018) 15 | */ 16 | public interface RoleService { 17 | 18 | // String findByRole(String role); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/RoleServiceImpl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.example.service; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Service; 10 | 11 | import com.example.model.Role; 12 | import com.example.repository.RoleRepository; 13 | 14 | /** 15 | * Implementation of the {@link RoleService} which accesses the {@link Role} 16 | * entity. This is the recommended way to access the entities through an 17 | * interface rather than using the corresponding repository. This allows for 18 | * separation into repository code and the service layer. 19 | * 20 | * @author Sunit Katkar 21 | * @version 1.0 22 | * @since 1.0 (April 2018) 23 | * 24 | */ 25 | @Service 26 | public class RoleServiceImpl implements RoleService { 27 | 28 | private static final Logger LOG = LoggerFactory.getLogger(RoleServiceImpl.class); 29 | 30 | @Autowired 31 | private RoleRepository roleRepository; 32 | 33 | public Role findByRole(String roleName) { 34 | Role role = roleRepository.findByRole(roleName); 35 | LOG.info("Role:" + role.getRole() + " found"); 36 | return role; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/UserService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.example.service; 5 | 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.data.repository.query.Param; 8 | 9 | import com.example.model.User; 10 | 11 | /** 12 | * Service definition which accesses the {@link com.example.model.User} entity. 13 | * This is the recommended way to access the entities through an interface 14 | * rather than using the corresponding repository directly. This allows for 15 | * separation into repository code and the service layer. 16 | * 17 | * @author Sunit Katkar 18 | * @version 1.0 19 | * @since 1.0 (April 2018) 20 | */ 21 | public interface UserService { 22 | 23 | void save(User user); 24 | 25 | String findLoggedInUsername(); 26 | 27 | @Query("select p from User p where p.username = :username and p.tenant = :tenant") 28 | User findByUsernameAndTenantname(@Param("username") String username, @Param("tenant") String tenant); 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/example/service/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.example.service; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.security.core.context.SecurityContextHolder; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 12 | import org.springframework.security.crypto.password.PasswordEncoder; 13 | import org.springframework.stereotype.Service; 14 | 15 | import com.example.model.User; 16 | import com.example.repository.RoleRepository; 17 | import com.example.repository.UserRepository; 18 | 19 | /** 20 | * Implementation of the {@link UserService} which accesses the {@link User} 21 | * entity. This is the recommended way to access the entities through an 22 | * interface rather than using the corresponding repository. This allows for 23 | * separation into repository code and the service layer. 24 | * 25 | * @author Sunit Katkar 26 | * @version 1.0 27 | * @since 1.0 (April 2018) 28 | */ 29 | @Service 30 | public class UserServiceImpl implements UserService { 31 | 32 | private static final Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class); 33 | 34 | @Autowired 35 | private UserRepository userRepository; 36 | 37 | @Autowired 38 | private RoleRepository roleRepository; 39 | 40 | @Autowired 41 | private PasswordEncoder passwordEncoder; 42 | 43 | /* 44 | * (non-Javadoc) 45 | * 46 | * @see com.example.service.UserService#save(com.example.model.User) 47 | */ 48 | @Override 49 | public void save(User user) { 50 | // TODO Auto-generated method stub 51 | 52 | } 53 | 54 | /* 55 | * (non-Javadoc) 56 | * 57 | * @see com.example.service.UserService#findLoggedInUsername() 58 | */ 59 | @Override 60 | public String findLoggedInUsername() { 61 | Object userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails(); 62 | if (userDetails instanceof UserDetails) { 63 | String username = ((UserDetails) userDetails).getUsername(); 64 | LOG.info("Logged in username:" + username); 65 | return username; 66 | } 67 | 68 | return null; 69 | } 70 | 71 | @Override 72 | public User findByUsernameAndTenantname(String username, String tenant) { 73 | User user = userRepository.findByUsernameAndTenantname(username, tenant); 74 | LOG.info("Found user with username:" + user.getUsername() + " from tenant:" + user.getTenant()); 75 | return user; 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/example/util/TenantContextHolder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.util; 17 | 18 | /** 19 | * When the end user submits the login form, the tenant id is required to 20 | * determine which database to connect to. This needs to be captured in the 21 | * spring security authentication mechanism, specifically in the 22 | * {@link UsernamePasswordAuthenticationFilter} implemented by 23 | * {@link CustomAuthenticationFilter}. This tenant id is then required by the 24 | * {@link CurrentTenantIdentifierResolver} implemeted by the 25 | * {@link CurrentTenantIdentifierResolverImpl} 26 | * 27 | *
28 | *
29 | * Explanation: Thread Local can be considered as a scope of access, like 30 | * a request scope or session scope. It’s a thread scope. You can set any object 31 | * in Thread Local and this object will be global and local to the specific 32 | * thread which is accessing this object. Global and local at the same time? : 33 | * 34 | *
    35 | *
  • Values stored in Thread Local are global to the thread, meaning that they 36 | * can be accessed from anywhere inside that thread. If a thread calls methods 37 | * from several classes, then all the methods can see the Thread Local variable 38 | * set by other methods (because they are executing in same thread). The value 39 | * need not be passed explicitly. It’s like how you use global variables.
  • 40 | *
  • Values stored in Thread Local are local to the thread, meaning that each 41 | * thread will have it’s own Thread Local variable. One thread can not 42 | * access/modify other thread’s Thread Local variables.
  • 43 | *
44 | * 45 | * @see https://dzone.com/articles/painless-introduction-javas-threadlocal-storage 46 | * @author Sunit Katkar 47 | * @version 1.0 48 | * @since 1.0 (April 2018) 49 | */ 50 | public class TenantContextHolder { 51 | 52 | private static final ThreadLocal CONTEXT = new ThreadLocal<>(); 53 | 54 | public static void setTenantId(String tenant) { 55 | CONTEXT.set(tenant); 56 | } 57 | 58 | public static String getTenant() { 59 | return CONTEXT.get(); 60 | } 61 | 62 | public static void clear() { 63 | CONTEXT.remove(); 64 | } 65 | } -------------------------------------------------------------------------------- /src/main/java/com/example/web/LoginController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.web; 17 | 18 | import java.util.Optional; 19 | 20 | import org.springframework.security.authentication.AnonymousAuthenticationToken; 21 | import org.springframework.security.core.Authentication; 22 | import org.springframework.security.core.context.SecurityContextHolder; 23 | import org.springframework.stereotype.Controller; 24 | import org.springframework.ui.Model; 25 | import org.springframework.web.bind.annotation.RequestMapping; 26 | 27 | import com.example.model.CustomUserDetails; 28 | 29 | @Controller 30 | public class LoginController { 31 | 32 | @RequestMapping("/") 33 | public String root() { 34 | return "redirect:/index"; 35 | } 36 | 37 | @RequestMapping("/index") 38 | public String index(Model model) { 39 | getLoggedInUsername().ifPresent(f -> { 40 | model.addAttribute("userName", f); 41 | }); 42 | getTenantName().ifPresent(d -> { 43 | model.addAttribute("tenantName", d); 44 | }); 45 | 46 | return "index"; 47 | } 48 | 49 | @RequestMapping("/user/index") 50 | public String userIndex(Model model) { 51 | getLoggedInUsername().ifPresent(f -> { 52 | model.addAttribute("userName", f); 53 | }); 54 | getTenantName().ifPresent(d -> { 55 | model.addAttribute("tenantName", d); 56 | }); 57 | return "user/index"; 58 | } 59 | 60 | @RequestMapping("/login") 61 | public String login() { 62 | return "login"; 63 | } 64 | 65 | private Optional getLoggedInUsername() { 66 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 67 | String userName = null; 68 | if (auth != null && !auth.getClass().equals(AnonymousAuthenticationToken.class)) { 69 | // User user = (User) auth.getPrincipal(); 70 | CustomUserDetails userDetails = (CustomUserDetails) auth.getPrincipal(); 71 | userName = userDetails.getUsername(); 72 | } 73 | 74 | return Optional.ofNullable(userName); 75 | } 76 | 77 | private Optional getTenantName() { 78 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 79 | String tenantName = null; 80 | if (auth != null && !auth.getClass().equals(AnonymousAuthenticationToken.class)) { 81 | // User user = (User) auth.getPrincipal(); 82 | CustomUserDetails userDetails = (CustomUserDetails) auth.getPrincipal(); 83 | tenantName = userDetails.getTenant(); 84 | } 85 | return Optional.ofNullable(tenantName); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | ######################################################################## 2 | ##### COPYRIGHT 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | ######################################################################## 4 | spring: 5 | thymeleaf: 6 | cache: false 7 | mode: LEGACYHTML5 8 | jpa: 9 | database: mysql 10 | show-sql: true 11 | generate-ddl: false 12 | hibernate: 13 | ddl-auto: none 14 | 15 | multitenancy: 16 | mtapp: 17 | dataSources: 18 | - 19 | tenantId: tenant_1 20 | url: jdbc:mysql://localhost:3306/dbtenant1?useSSL=false 21 | username: tenant1 22 | password: admin123 23 | driverClassName: com.mysql.jdbc.Driver 24 | - 25 | tenantId: tenant_2 26 | url: jdbc:mysql://localhost:3306/dbtenant2?useSSL=false 27 | username: tenant1 28 | password: admin123 29 | driverClassName: com.mysql.jdbc.Driver -------------------------------------------------------------------------------- /src/main/resources/static/css/main.css: -------------------------------------------------------------------------------- 1 | p.error { 2 | font-weight: bold; 3 | color: red; 4 | } 5 | 6 | div.logout { 7 | margin-right: 2em;; 8 | } -------------------------------------------------------------------------------- /src/main/resources/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | Spring Security with Extra Fields 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 |
17 |

Logged in: Username | | Some Domain 18 |

19 |
20 |
21 | 22 |
23 |
24 |
25 | 26 |

Hello Spring Security

27 |

This is an unsecured page, but you can access the secured pages after authenticating.

28 | 31 |
32 | 33 | -------------------------------------------------------------------------------- /src/main/resources/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Login page 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 34 |
35 | 36 | -------------------------------------------------------------------------------- /src/main/resources/templates/user/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Secured Page 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 |

This is a secured page for Some Domain and username is Username

17 |

Back to home page

18 |
19 | 20 | -------------------------------------------------------------------------------- /src/test/java/com/example/MultitenancyMySqlApplicationTests.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 onwards - Sunit Katkar (sunitkatkar@gmail.com) 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example; 17 | 18 | import org.junit.Test; 19 | import org.junit.runner.RunWith; 20 | import org.springframework.boot.test.context.SpringBootTest; 21 | import org.springframework.test.context.junit4.SpringRunner; 22 | 23 | @RunWith(SpringRunner.class) 24 | @SpringBootTest 25 | public class MultitenancyMySqlApplicationTests { 26 | 27 | @Test 28 | public void contextLoads() { 29 | } 30 | 31 | } 32 | --------------------------------------------------------------------------------