Merge pull request #15669 from hmdrzsharifi/BAEL-7434

Bael 7434: Verify code for "Multitenancy With Spring Data JPA"
This commit is contained in:
davidmartinezbarua 2024-02-02 13:21:41 -03:00 committed by GitHub
commit 772649421b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 51 additions and 19 deletions

View File

@ -55,7 +55,7 @@
<dependency> <dependency>
<groupId>io.jsonwebtoken</groupId> <groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId> <artifactId>jjwt-api</artifactId>
<version>0.12.3</version> <version>${jjwt.version}</version>
</dependency> </dependency>
<!-- persistence --> <!-- persistence -->
<dependency> <dependency>
@ -107,6 +107,18 @@
<artifactId>jackson-core</artifactId> <artifactId>jackson-core</artifactId>
<version>${jakson-core.version}</version> <version>${jakson-core.version}</version>
</dependency> </dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
@ -115,8 +127,11 @@
<spring-boot.version>3.1.0</spring-boot.version> <spring-boot.version>3.1.0</spring-boot.version>
<!-- persistence --> <!-- persistence -->
<tomcat-dbcp.version>10.1.9</tomcat-dbcp.version> <tomcat-dbcp.version>10.1.9</tomcat-dbcp.version>
<jakson-databind.version>2.15.1</jakson-databind.version> <jakson-databind.version>2.16.1</jakson-databind.version>
<jakson-core.version>2.14.2</jakson-core.version> <jakson-core.version>2.16.1</jakson-core.version>
<jjwt.version>0.12.3</jjwt.version>
<logback.version>1.4.14</logback.version>
</properties> </properties>
</project> </project>

View File

@ -1,5 +1,6 @@
package com.baeldung.multitenant.config; package com.baeldung.multitenant.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@ -18,6 +19,9 @@ import java.util.Properties;
@Configuration @Configuration
public class MultitenantConfiguration { public class MultitenantConfiguration {
@Value("${defaultTenant}")
private String defaultTenant;
@Bean @Bean
@ConfigurationProperties(prefix = "tenants") @ConfigurationProperties(prefix = "tenants")
public DataSource dataSource() { public DataSource dataSource() {
@ -43,7 +47,7 @@ public class MultitenantConfiguration {
} }
AbstractRoutingDataSource dataSource = new MultitenantDataSource(); AbstractRoutingDataSource dataSource = new MultitenantDataSource();
dataSource.setDefaultTargetDataSource(resolvedDataSources.get("tenant_1")); dataSource.setDefaultTargetDataSource(resolvedDataSources.get(defaultTenant));
dataSource.setTargetDataSources(resolvedDataSources); dataSource.setTargetDataSources(resolvedDataSources);
dataSource.afterPropertiesSet(); dataSource.afterPropertiesSet();

View File

@ -1,26 +1,31 @@
package com.baeldung.multitenant.security; package com.baeldung.multitenant.security;
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import jakarta.servlet.http.HttpServletRequest; import javax.crypto.SecretKey;
import jakarta.servlet.http.HttpServletResponse; import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
public class AuthenticationService { public class AuthenticationService {
private static final long EXPIRATIONTIME = 864_000_00; // 1 day in milliseconds private static final long EXPIRATIONTIME = 864_000_00; // 1 day in milliseconds
private static final String SIGNINGKEY = "SecretKey"; private static final String SECRETKEY = "q3t6w9zCFJNcQfTjWnq3t6w9zCFJNcQfTjWnZr4u7xADGKaPd";
private static final SecretKey SIGNINGKEY = Keys.hmacShaKeyFor(SECRETKEY.getBytes(StandardCharsets.UTF_8));
private static final String PREFIX = "Bearer"; private static final String PREFIX = "Bearer";
public static void addToken(HttpServletResponse res, String username, String tenant) { public static void addToken(HttpServletResponse res, String username, String tenant) {
String JwtToken = Jwts.builder().setSubject(username) String JwtToken = Jwts.builder()
.setAudience(tenant) .subject(username)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME)) .audience().add(tenant).and()
.signWith(SignatureAlgorithm.HS512, SIGNINGKEY) .issuedAt(new Date(System.currentTimeMillis()))
.expiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
.signWith(SIGNINGKEY)
.compact(); .compact();
res.addHeader("Authorization", PREFIX + " " + JwtToken); res.addHeader("Authorization", PREFIX + " " + JwtToken);
} }
@ -29,9 +34,8 @@ public class AuthenticationService {
String token = req.getHeader("Authorization"); String token = req.getHeader("Authorization");
if (token != null) { if (token != null) {
String user = Jwts.parser() String user = Jwts.parser()
.setSigningKey(SIGNINGKEY) .verifyWith(SIGNINGKEY)
.build().parseClaimsJws(token.replace(PREFIX, "")) .build().parseClaimsJws(token.replace(PREFIX, "").trim()).getPayload()
.getBody()
.getSubject(); .getSubject();
if (user != null) { if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList()); return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
@ -48,7 +52,7 @@ public class AuthenticationService {
} }
String tenant = Jwts.parser() String tenant = Jwts.parser()
.setSigningKey(SIGNINGKEY) .setSigningKey(SIGNINGKEY)
.build().parseClaimsJws(token.replace(PREFIX, "")) .build().parseClaimsJws(token.replace(PREFIX, "").trim())
.getBody() .getBody()
.getAudience() .getAudience()
.iterator() .iterator()

View File

@ -4,9 +4,9 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer; import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer; import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
@ -42,16 +42,21 @@ public class SecurityConfiguration {
return new BCryptPasswordEncoder(); return new BCryptPasswordEncoder();
} }
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean @Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
final AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class); final AuthenticationManager authenticationManager = authenticationManager(http.getSharedObject(AuthenticationConfiguration.class));
http http
.authorizeHttpRequests(authorize -> .authorizeHttpRequests(authorize ->
authorize.requestMatchers("/login").permitAll().anyRequest().authenticated()) authorize.requestMatchers("/login").permitAll().anyRequest().authenticated())
.sessionManagement(securityContext -> securityContext.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .sessionManagement(securityContext -> securityContext.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(new LoginFilter("/login", authenticationManager), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(new LoginFilter("/login", authenticationManager), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new AuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(new AuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.csrf(AbstractHttpConfigurer::disable) .csrf(csrf -> csrf.disable())
.headers(header -> header.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) .headers(header -> header.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
.httpBasic(Customizer.withDefaults()); .httpBasic(Customizer.withDefaults());

View File

@ -9,3 +9,7 @@ spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
#spring.datasource.username=mysqluser #spring.datasource.username=mysqluser
#spring.datasource.password=mysqlpass #spring.datasource.password=mysqlpass
#spring.datasource.url=jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true #spring.datasource.url=jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true
# MultiTenantApplication
defaultTenant=tenant_1
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect