├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── src ├── main │ ├── java │ │ └── com │ │ │ └── alonsegal │ │ │ ├── multitenancy │ │ │ ├── MultiTenantConstants.java │ │ │ ├── TenantIdentifierResolver.java │ │ │ ├── TenantNameFetcher.java │ │ │ ├── TenantContext.java │ │ │ ├── UnboundTenantTask.java │ │ │ ├── TenantInterceptor.java │ │ │ └── MultiTenantConnectionProviderImpl.java │ │ │ ├── SpringbootSchemaPerTenantApplication.java │ │ │ ├── repository │ │ │ └── UserTenantRelationRepository.java │ │ │ ├── jwt │ │ │ ├── JwtAuthenticationResponse.java │ │ │ └── JwtAuthenticationRequest.java │ │ │ ├── config │ │ │ ├── MvcConfig.java │ │ │ └── HibernateConfig.java │ │ │ ├── domain │ │ │ └── UserTenantRelation.java │ │ │ └── web │ │ │ └── LoginController.java │ └── resources │ │ └── application.properties └── test │ └── java │ └── com │ └── alonsegal │ └── SpringbootSchemaPerTenantApplicationTests.java ├── .gitignore ├── README.md ├── pom.xml ├── mvnw.cmd └── mvnw /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alonsegal/springboot-schema-per-tenant/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip 2 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/multitenancy/MultiTenantConstants.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.multitenancy; 2 | 3 | public interface MultiTenantConstants { 4 | 5 | String DEFAULT_TENANT_ID = "default_tenant"; 6 | } 7 | -------------------------------------------------------------------------------- /.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 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | jwt.header=Authorization 2 | jwt.secret=mysecret 3 | jwt.expiration=3600 4 | 5 | spring.datasource.url-base=jdbc:mysql://localhost:3306 6 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 7 | spring.datasource.url=${spring.datasource.url-base} 8 | spring.datasource.username=root 9 | spring.datasource.password= 10 | 11 | spring.jpa.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/SpringbootSchemaPerTenantApplication.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringbootSchemaPerTenantApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringbootSchemaPerTenantApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/repository/UserTenantRelationRepository.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.repository; 2 | 3 | import com.alonsegal.domain.UserTenantRelation; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | /** 7 | * Created by Alon Segal on 23/03/2017. 8 | */ 9 | public interface UserTenantRelationRepository extends JpaRepository { 10 | 11 | UserTenantRelation findByUsername(String name); 12 | } 13 | -------------------------------------------------------------------------------- /src/test/java/com/alonsegal/SpringbootSchemaPerTenantApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringbootSchemaPerTenantApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/jwt/JwtAuthenticationResponse.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.jwt; 2 | 3 | import org.springframework.security.core.userdetails.UserDetails; 4 | 5 | import java.io.Serializable; 6 | 7 | /** 8 | * Created by stephan on 20.03.16. 9 | */ 10 | public class JwtAuthenticationResponse implements Serializable { 11 | 12 | private static final long serialVersionUID = 1250166508152483573L; 13 | 14 | private final String token; 15 | private final UserDetails user; 16 | 17 | public JwtAuthenticationResponse(String token, UserDetails user) { 18 | this.token = token; 19 | this.user = user; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/config/MvcConfig.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.servlet.HandlerInterceptor; 6 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 8 | 9 | @Configuration 10 | public class MvcConfig extends WebMvcConfigurerAdapter { 11 | 12 | @Autowired 13 | HandlerInterceptor tenantInterceptor; 14 | 15 | @Override 16 | public void addInterceptors(InterceptorRegistry registry) { 17 | registry.addInterceptor(tenantInterceptor); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/multitenancy/TenantIdentifierResolver.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.multitenancy; 2 | 3 | import org.hibernate.context.spi.CurrentTenantIdentifierResolver; 4 | import org.springframework.stereotype.Component; 5 | 6 | import static com.alonsegal.multitenancy.MultiTenantConstants.DEFAULT_TENANT_ID; 7 | 8 | @Component 9 | public class TenantIdentifierResolver implements CurrentTenantIdentifierResolver { 10 | 11 | @Override 12 | public String resolveCurrentTenantIdentifier() { 13 | String tenantId = TenantContext.getCurrentTenant(); 14 | if (tenantId != null) { 15 | return tenantId; 16 | } 17 | return DEFAULT_TENANT_ID; 18 | } 19 | 20 | @Override 21 | public boolean validateExistingCurrentSessions() { 22 | return true; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/multitenancy/TenantNameFetcher.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.multitenancy; 2 | 3 | import com.alonsegal.domain.UserTenantRelation; 4 | import com.alonsegal.repository.UserTenantRelationRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Component; 7 | 8 | /** 9 | * Created by Alon Segal on 24/03/2017. 10 | */ 11 | @Component 12 | public class TenantNameFetcher extends UnboundTenantTask { 13 | 14 | @Autowired 15 | private UserTenantRelationRepository userTenantRelationRepository; 16 | 17 | @Override 18 | protected UserTenantRelation callInternal() { 19 | UserTenantRelation utr = userTenantRelationRepository.findByUsername(this.username); 20 | return utr; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/multitenancy/TenantContext.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.multitenancy; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | /** 7 | * Created by Alon Segal on 16/03/2017. 8 | */ 9 | public class TenantContext { 10 | 11 | private static Logger logger = LoggerFactory.getLogger(TenantContext.class.getName()); 12 | 13 | private static ThreadLocal currentTenant = new ThreadLocal<>(); 14 | 15 | public static void setCurrentTenant(String tenant) { 16 | logger.debug("Setting tenant to " + tenant); 17 | currentTenant.set(tenant); 18 | } 19 | 20 | public static String getCurrentTenant() { 21 | return currentTenant.get(); 22 | } 23 | 24 | public static void clear() { 25 | currentTenant.set(null); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # springboot-schema-per-tenant 2 | Seed project for achieving multi-tenancy (single pooled schema-per-tenant) using SpringBoot and Hibernate as proposed in [this article](https://dzone.com/articles/spring-boot-hibernate-multitenancy-implementation). 3 | 4 | This project assumes a dedicated MySql DB is reachable (can be configured in application.properties), which has a default schema named `default_schema` and at least one additional schema with some tenant name you choose. 5 | 6 | The default schema has a single table called `user_tenant_relation` and has the following structure: 7 | 8 | ``` 9 | CREATE TABLE `user_tenant_relation` ( 10 | `id` int(11) NOT NULL AUTO_INCREMENT, 11 | `username` varchar(45) NOT NULL, 12 | `tenant` varchar(45) NOT NULL, 13 | PRIMARY KEY (`id`), 14 | UNIQUE KEY `username_tenent_uq` (`username`,`tenant`) 15 | ); 16 | ``` 17 | 18 | The JWT boiler-plate code is removed from to keep it clear and as simple as possible. -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/jwt/JwtAuthenticationRequest.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.jwt; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * Created by stephan on 20.03.16. 7 | */ 8 | public class JwtAuthenticationRequest implements Serializable { 9 | 10 | private String username; 11 | private String password; 12 | 13 | public JwtAuthenticationRequest() { 14 | super(); 15 | } 16 | 17 | public JwtAuthenticationRequest(String username, String password) { 18 | this.setUsername(username); 19 | this.setPassword(password); 20 | } 21 | 22 | public String getUsername() { 23 | return this.username; 24 | } 25 | 26 | public void setUsername(String username) { 27 | this.username = username; 28 | } 29 | 30 | public String getPassword() { 31 | return this.password; 32 | } 33 | 34 | public void setPassword(String password) { 35 | this.password = password; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/multitenancy/UnboundTenantTask.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.multitenancy; 2 | 3 | import java.util.concurrent.Callable; 4 | 5 | import static com.alonsegal.multitenancy.MultiTenantConstants.DEFAULT_TENANT_ID; 6 | 7 | /** 8 | * This is a workaround to resolve the issue with Hibernate where only a 9 | * tenant cannot be changed in a single context. 10 | * 11 | * Issue: https://hibernate.atlassian.net/browse/HHH-9766 12 | * Solution taken from: http://stackoverflow.com/questions/30757344/hibernate-multitenancy-change-tenant-in-session/ 13 | * 14 | * Created by Alon Segal on 24/03/2017. 15 | */ 16 | public abstract class UnboundTenantTask implements Callable { 17 | 18 | protected String username; 19 | 20 | public void setUsername(String username) { 21 | this.username = username; 22 | } 23 | 24 | @Override 25 | public T call() throws Exception { 26 | TenantContext.setCurrentTenant(DEFAULT_TENANT_ID); 27 | return callInternal(); 28 | } 29 | 30 | protected abstract T callInternal(); 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/domain/UserTenantRelation.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.domain; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.Id; 5 | 6 | /** 7 | * Created by Alon Segal on 23/03/2017. 8 | */ 9 | @Entity 10 | public class UserTenantRelation { 11 | 12 | private Integer id; 13 | private String username; 14 | private String tenant; 15 | 16 | public UserTenantRelation() { 17 | } 18 | 19 | public UserTenantRelation(Integer id, String username, String tenant) { 20 | this.id = id; 21 | this.username = username; 22 | this.tenant = tenant; 23 | } 24 | 25 | @Id 26 | public Integer getId() { 27 | return id; 28 | } 29 | 30 | public void setId(Integer id) { 31 | this.id = id; 32 | } 33 | 34 | public String getUsername() { 35 | return username; 36 | } 37 | 38 | public void setUsername(String username) { 39 | this.username = username; 40 | } 41 | 42 | public String getTenant() { 43 | return tenant; 44 | } 45 | 46 | public void setTenant(String tenant) { 47 | this.tenant = tenant; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/multitenancy/TenantInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.multitenancy; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.stereotype.Component; 5 | import org.springframework.web.servlet.ModelAndView; 6 | import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | import javax.servlet.http.HttpServletResponse; 10 | 11 | /** 12 | * Created by Alon Segal on 23/03/2017. 13 | */ 14 | 15 | @Component 16 | public class TenantInterceptor extends HandlerInterceptorAdapter { 17 | 18 | @Value("${jwt.header}") 19 | private String tokenHeader; 20 | 21 | @Override 22 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 23 | throws Exception { 24 | 25 | String authToken = request.getHeader(this.tokenHeader); 26 | // authToken.startsWith("Bearer ") 27 | // String authToken = header.substring(7); 28 | String tenantId = "tenantId from authToken";//jwtTokenUtil.getTenantIdFromToken(authToken); 29 | TenantContext.setCurrentTenant(tenantId); 30 | 31 | return true; 32 | } 33 | 34 | @Override 35 | public void postHandle( 36 | HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) 37 | throws Exception { 38 | TenantContext.clear(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/config/HibernateConfig.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.config; 2 | 3 | import org.hibernate.MultiTenancyStrategy; 4 | import org.hibernate.cfg.Environment; 5 | import org.hibernate.context.spi.CurrentTenantIdentifierResolver; 6 | import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.orm.jpa.JpaVendorAdapter; 12 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; 13 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; 14 | 15 | import javax.sql.DataSource; 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | /** 20 | * Created by Alon Segal on 23/03/2017. 21 | */ 22 | @Configuration 23 | public class HibernateConfig { 24 | 25 | @Autowired 26 | private JpaProperties jpaProperties; 27 | 28 | @Bean 29 | public JpaVendorAdapter jpaVendorAdapter() { 30 | return new HibernateJpaVendorAdapter(); 31 | } 32 | 33 | @Bean 34 | public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, 35 | MultiTenantConnectionProvider multiTenantConnectionProviderImpl, 36 | CurrentTenantIdentifierResolver currentTenantIdentifierResolverImpl) { 37 | Map properties = new HashMap<>(); 38 | properties.putAll(jpaProperties.getHibernateProperties(dataSource)); 39 | properties.put(Environment.MULTI_TENANT, MultiTenancyStrategy.SCHEMA); 40 | properties.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProviderImpl); 41 | properties.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolverImpl); 42 | 43 | LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); 44 | em.setDataSource(dataSource); 45 | em.setPackagesToScan("com.alonsegal"); 46 | em.setJpaVendorAdapter(jpaVendorAdapter()); 47 | em.setJpaPropertyMap(properties); 48 | return em; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/multitenancy/MultiTenantConnectionProviderImpl.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.multitenancy; 2 | 3 | import org.hibernate.HibernateException; 4 | import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Component; 7 | 8 | import javax.sql.DataSource; 9 | import java.sql.Connection; 10 | import java.sql.SQLException; 11 | 12 | import static com.alonsegal.multitenancy.MultiTenantConstants.DEFAULT_TENANT_ID; 13 | 14 | @Component 15 | public class MultiTenantConnectionProviderImpl implements MultiTenantConnectionProvider { 16 | 17 | @Autowired 18 | private DataSource dataSource; 19 | 20 | @Override 21 | public Connection getAnyConnection() throws SQLException { 22 | return dataSource.getConnection(); 23 | } 24 | 25 | @Override 26 | public void releaseAnyConnection(Connection connection) throws SQLException { 27 | connection.close(); 28 | } 29 | 30 | @Override 31 | public Connection getConnection(String tenantIdentifier) throws SQLException { 32 | final Connection connection = getAnyConnection(); 33 | try { 34 | if (tenantIdentifier != null) { 35 | connection.createStatement().execute("USE " + tenantIdentifier); 36 | } else { 37 | connection.createStatement().execute("USE " + DEFAULT_TENANT_ID); 38 | } 39 | } 40 | catch ( SQLException e ) { 41 | throw new HibernateException( 42 | "Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]", 43 | e 44 | ); 45 | } 46 | return connection; 47 | } 48 | 49 | @Override 50 | public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException { 51 | try { 52 | connection.createStatement().execute( "USE " + DEFAULT_TENANT_ID ); 53 | } 54 | catch ( SQLException e ) { 55 | throw new HibernateException( 56 | "Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]", 57 | e 58 | ); 59 | } 60 | connection.close(); 61 | } 62 | 63 | @SuppressWarnings("rawtypes") 64 | @Override 65 | public boolean isUnwrappableAs(Class unwrapType) { 66 | return false; 67 | } 68 | 69 | @Override 70 | public T unwrap(Class unwrapType) { 71 | return null; 72 | } 73 | 74 | @Override 75 | public boolean supportsAggressiveRelease() { 76 | return true; 77 | } 78 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.alonsegal 7 | springboot-schema-per-tenant 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | springboot-schema-per-tenant 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.2.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 5.1.6 26 | 0.7.0 27 | 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-data-jpa 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-web 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-security 41 | 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-test 46 | test 47 | 48 | 49 | 50 | mysql 51 | mysql-connector-java 52 | ${mysql-connector-java-version} 53 | 54 | 55 | 56 | io.jsonwebtoken 57 | jjwt 58 | ${jjwt.version} 59 | 60 | 61 | 62 | joda-time 63 | joda-time 64 | 2.9.7 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | org.springframework.boot 73 | spring-boot-maven-plugin 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /src/main/java/com/alonsegal/web/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.alonsegal.web; 2 | 3 | import com.alonsegal.domain.UserTenantRelation; 4 | import com.alonsegal.multitenancy.TenantContext; 5 | import com.alonsegal.multitenancy.TenantNameFetcher; 6 | import com.alonsegal.jwt.JwtAuthenticationRequest; 7 | import com.alonsegal.jwt.JwtAuthenticationResponse; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.http.HttpStatus; 11 | import org.springframework.http.ResponseEntity; 12 | import org.springframework.security.authentication.AuthenticationManager; 13 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 14 | import org.springframework.security.core.Authentication; 15 | import org.springframework.security.core.AuthenticationException; 16 | import org.springframework.security.core.context.SecurityContextHolder; 17 | import org.springframework.security.core.userdetails.UserDetails; 18 | import org.springframework.web.bind.annotation.RequestBody; 19 | import org.springframework.web.bind.annotation.RequestMapping; 20 | import org.springframework.web.bind.annotation.RequestMethod; 21 | import org.springframework.web.bind.annotation.RestController; 22 | import javax.servlet.http.Cookie; 23 | import javax.servlet.http.HttpServletResponse; 24 | import java.util.concurrent.ExecutorService; 25 | import java.util.concurrent.Executors; 26 | import java.util.concurrent.Future; 27 | 28 | @RestController 29 | public class LoginController { 30 | 31 | @Value("${jwt.header}") 32 | private String tokenHeader; 33 | 34 | @Autowired 35 | private AuthenticationManager authenticationManager; 36 | 37 | @Autowired 38 | private TenantNameFetcher tenantResolver; 39 | 40 | @RequestMapping(value = "auth", method = RequestMethod.POST) 41 | public ResponseEntity createAuthenticationToken( 42 | @RequestBody JwtAuthenticationRequest authenticationRequest, 43 | HttpServletResponse response) throws AuthenticationException { 44 | //Resolve the user's tenantId 45 | try { 46 | tenantResolver.setUsername(authenticationRequest.getUsername()); 47 | ExecutorService es = Executors.newSingleThreadExecutor(); 48 | Future utrFuture = es.submit(tenantResolver); 49 | UserTenantRelation utr = utrFuture.get(); 50 | es.shutdown(); 51 | //TODO: handle utr == null, user is not found 52 | //Got the tenant, now switch to the context 53 | TenantContext.setCurrentTenant(utr.getTenant()); 54 | } catch (Exception e) { 55 | e.printStackTrace(); 56 | } 57 | 58 | // Perform the authentication 59 | try { 60 | final Authentication authentication = authenticationManager.authenticate( 61 | new UsernamePasswordAuthenticationToken( 62 | authenticationRequest.getUsername(), 63 | authenticationRequest.getPassword() 64 | ) 65 | ); 66 | SecurityContextHolder.getContext().setAuthentication(authentication); 67 | } catch (Exception e) { 68 | return new ResponseEntity(HttpStatus.UNAUTHORIZED); 69 | } 70 | 71 | //Generate JWT for user and send it as a Secured & HttpOnly cookie 72 | final UserDetails user = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 73 | final String token = "generated_jwt_token";//jwtTokenUtil.generateToken(user); 74 | Cookie cookie = new Cookie(tokenHeader, token); 75 | cookie.setHttpOnly(true); 76 | cookie.setSecure(true); 77 | cookie.setPath("/"); 78 | response.addCookie(cookie); 79 | 80 | return new ResponseEntity<>(new JwtAuthenticationResponse(token, user), HttpStatus.OK); 81 | } 82 | } -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | set MAVEN_CMD_LINE_ARGS=%* 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | 121 | set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" 122 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 123 | 124 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% 125 | if ERRORLEVEL 1 goto error 126 | goto end 127 | 128 | :error 129 | set ERROR_CODE=1 130 | 131 | :end 132 | @endlocal & set ERROR_CODE=%ERROR_CODE% 133 | 134 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 135 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 136 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 137 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 138 | :skipRcPost 139 | 140 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 141 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 142 | 143 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 144 | 145 | exit /B %ERROR_CODE% -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # 58 | # Look for the Apple JDKs first to preserve the existing behaviour, and then look 59 | # for the new JDKs provided by Oracle. 60 | # 61 | if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then 62 | # 63 | # Apple JDKs 64 | # 65 | export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home 66 | fi 67 | 68 | if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then 69 | # 70 | # Apple JDKs 71 | # 72 | export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home 73 | fi 74 | 75 | if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then 76 | # 77 | # Oracle JDKs 78 | # 79 | export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home 80 | fi 81 | 82 | if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then 83 | # 84 | # Apple JDKs 85 | # 86 | export JAVA_HOME=`/usr/libexec/java_home` 87 | fi 88 | ;; 89 | esac 90 | 91 | if [ -z "$JAVA_HOME" ] ; then 92 | if [ -r /etc/gentoo-release ] ; then 93 | JAVA_HOME=`java-config --jre-home` 94 | fi 95 | fi 96 | 97 | if [ -z "$M2_HOME" ] ; then 98 | ## resolve links - $0 may be a link to maven's home 99 | PRG="$0" 100 | 101 | # need this for relative symlinks 102 | while [ -h "$PRG" ] ; do 103 | ls=`ls -ld "$PRG"` 104 | link=`expr "$ls" : '.*-> \(.*\)$'` 105 | if expr "$link" : '/.*' > /dev/null; then 106 | PRG="$link" 107 | else 108 | PRG="`dirname "$PRG"`/$link" 109 | fi 110 | done 111 | 112 | saveddir=`pwd` 113 | 114 | M2_HOME=`dirname "$PRG"`/.. 115 | 116 | # make it fully qualified 117 | M2_HOME=`cd "$M2_HOME" && pwd` 118 | 119 | cd "$saveddir" 120 | # echo Using m2 at $M2_HOME 121 | fi 122 | 123 | # For Cygwin, ensure paths are in UNIX format before anything is touched 124 | if $cygwin ; then 125 | [ -n "$M2_HOME" ] && 126 | M2_HOME=`cygpath --unix "$M2_HOME"` 127 | [ -n "$JAVA_HOME" ] && 128 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 129 | [ -n "$CLASSPATH" ] && 130 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 131 | fi 132 | 133 | # For Migwn, ensure paths are in UNIX format before anything is touched 134 | if $mingw ; then 135 | [ -n "$M2_HOME" ] && 136 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 137 | [ -n "$JAVA_HOME" ] && 138 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 139 | # TODO classpath? 140 | fi 141 | 142 | if [ -z "$JAVA_HOME" ]; then 143 | javaExecutable="`which javac`" 144 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 145 | # readlink(1) is not available as standard on Solaris 10. 146 | readLink=`which readlink` 147 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 148 | if $darwin ; then 149 | javaHome="`dirname \"$javaExecutable\"`" 150 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 151 | else 152 | javaExecutable="`readlink -f \"$javaExecutable\"`" 153 | fi 154 | javaHome="`dirname \"$javaExecutable\"`" 155 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 156 | JAVA_HOME="$javaHome" 157 | export JAVA_HOME 158 | fi 159 | fi 160 | fi 161 | 162 | if [ -z "$JAVACMD" ] ; then 163 | if [ -n "$JAVA_HOME" ] ; then 164 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 165 | # IBM's JDK on AIX uses strange locations for the executables 166 | JAVACMD="$JAVA_HOME/jre/sh/java" 167 | else 168 | JAVACMD="$JAVA_HOME/bin/java" 169 | fi 170 | else 171 | JAVACMD="`which java`" 172 | fi 173 | fi 174 | 175 | if [ ! -x "$JAVACMD" ] ; then 176 | echo "Error: JAVA_HOME is not defined correctly." >&2 177 | echo " We cannot execute $JAVACMD" >&2 178 | exit 1 179 | fi 180 | 181 | if [ -z "$JAVA_HOME" ] ; then 182 | echo "Warning: JAVA_HOME environment variable is not set." 183 | fi 184 | 185 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 186 | 187 | # For Cygwin, switch paths to Windows format before running java 188 | if $cygwin; then 189 | [ -n "$M2_HOME" ] && 190 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 191 | [ -n "$JAVA_HOME" ] && 192 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 193 | [ -n "$CLASSPATH" ] && 194 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 195 | fi 196 | 197 | # traverses directory structure from process work directory to filesystem root 198 | # first directory with .mvn subdirectory is considered project base directory 199 | find_maven_basedir() { 200 | local basedir=$(pwd) 201 | local wdir=$(pwd) 202 | while [ "$wdir" != '/' ] ; do 203 | if [ -d "$wdir"/.mvn ] ; then 204 | basedir=$wdir 205 | break 206 | fi 207 | wdir=$(cd "$wdir/.."; pwd) 208 | done 209 | echo "${basedir}" 210 | } 211 | 212 | # concatenates all lines of a file 213 | concat_lines() { 214 | if [ -f "$1" ]; then 215 | echo "$(tr -s '\n' ' ' < "$1")" 216 | fi 217 | } 218 | 219 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} 220 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 221 | 222 | # Provide a "standardized" way to retrieve the CLI args that will 223 | # work with both Windows and non-Windows executions. 224 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 225 | export MAVEN_CMD_LINE_ARGS 226 | 227 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 228 | 229 | exec "$JAVACMD" \ 230 | $MAVEN_OPTS \ 231 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 232 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 233 | ${WRAPPER_LAUNCHER} "$@" 234 | --------------------------------------------------------------------------------