Merge pull request #15669 from hmdrzsharifi/BAEL-7434
Bael 7434: Verify code for "Multitenancy With Spring Data JPA"
This commit is contained in:
commit
772649421b
|
@ -55,7 +55,7 @@
|
|||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>0.12.3</version>
|
||||
<version>${jjwt.version}</version>
|
||||
</dependency>
|
||||
<!-- persistence -->
|
||||
<dependency>
|
||||
|
@ -107,6 +107,18 @@
|
|||
<artifactId>jackson-core</artifactId>
|
||||
<version>${jakson-core.version}</version>
|
||||
</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>
|
||||
|
||||
<properties>
|
||||
|
@ -115,8 +127,11 @@
|
|||
<spring-boot.version>3.1.0</spring-boot.version>
|
||||
<!-- persistence -->
|
||||
<tomcat-dbcp.version>10.1.9</tomcat-dbcp.version>
|
||||
<jakson-databind.version>2.15.1</jakson-databind.version>
|
||||
<jakson-core.version>2.14.2</jakson-core.version>
|
||||
<jakson-databind.version>2.16.1</jakson-databind.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>
|
||||
|
||||
</project>
|
|
@ -1,5 +1,6 @@
|
|||
package com.baeldung.multitenant.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
@ -18,6 +19,9 @@ import java.util.Properties;
|
|||
@Configuration
|
||||
public class MultitenantConfiguration {
|
||||
|
||||
@Value("${defaultTenant}")
|
||||
private String defaultTenant;
|
||||
|
||||
@Bean
|
||||
@ConfigurationProperties(prefix = "tenants")
|
||||
public DataSource dataSource() {
|
||||
|
@ -43,7 +47,7 @@ public class MultitenantConfiguration {
|
|||
}
|
||||
|
||||
AbstractRoutingDataSource dataSource = new MultitenantDataSource();
|
||||
dataSource.setDefaultTargetDataSource(resolvedDataSources.get("tenant_1"));
|
||||
dataSource.setDefaultTargetDataSource(resolvedDataSources.get(defaultTenant));
|
||||
dataSource.setTargetDataSources(resolvedDataSources);
|
||||
|
||||
dataSource.afterPropertiesSet();
|
||||
|
|
|
@ -1,26 +1,31 @@
|
|||
package com.baeldung.multitenant.security;
|
||||
|
||||
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.core.Authentication;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
|
||||
public class AuthenticationService {
|
||||
|
||||
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";
|
||||
|
||||
public static void addToken(HttpServletResponse res, String username, String tenant) {
|
||||
String JwtToken = Jwts.builder().setSubject(username)
|
||||
.setAudience(tenant)
|
||||
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
|
||||
.signWith(SignatureAlgorithm.HS512, SIGNINGKEY)
|
||||
String JwtToken = Jwts.builder()
|
||||
.subject(username)
|
||||
.audience().add(tenant).and()
|
||||
.issuedAt(new Date(System.currentTimeMillis()))
|
||||
.expiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
|
||||
.signWith(SIGNINGKEY)
|
||||
.compact();
|
||||
res.addHeader("Authorization", PREFIX + " " + JwtToken);
|
||||
}
|
||||
|
@ -29,9 +34,8 @@ public class AuthenticationService {
|
|||
String token = req.getHeader("Authorization");
|
||||
if (token != null) {
|
||||
String user = Jwts.parser()
|
||||
.setSigningKey(SIGNINGKEY)
|
||||
.build().parseClaimsJws(token.replace(PREFIX, ""))
|
||||
.getBody()
|
||||
.verifyWith(SIGNINGKEY)
|
||||
.build().parseClaimsJws(token.replace(PREFIX, "").trim()).getPayload()
|
||||
.getSubject();
|
||||
if (user != null) {
|
||||
return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
|
||||
|
@ -48,7 +52,7 @@ public class AuthenticationService {
|
|||
}
|
||||
String tenant = Jwts.parser()
|
||||
.setSigningKey(SIGNINGKEY)
|
||||
.build().parseClaimsJws(token.replace(PREFIX, ""))
|
||||
.build().parseClaimsJws(token.replace(PREFIX, "").trim())
|
||||
.getBody()
|
||||
.getAudience()
|
||||
.iterator()
|
||||
|
|
|
@ -4,9 +4,9 @@ import org.springframework.context.annotation.Bean;
|
|||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
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.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.http.SessionCreationPolicy;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
|
@ -42,16 +42,21 @@ public class SecurityConfiguration {
|
|||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
|
||||
return authenticationConfiguration.getAuthenticationManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
final AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
|
||||
final AuthenticationManager authenticationManager = authenticationManager(http.getSharedObject(AuthenticationConfiguration.class));
|
||||
http
|
||||
.authorizeHttpRequests(authorize ->
|
||||
authorize.requestMatchers("/login").permitAll().anyRequest().authenticated())
|
||||
.sessionManagement(securityContext -> securityContext.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.addFilterBefore(new LoginFilter("/login", authenticationManager), UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(new AuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.headers(header -> header.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
|
||||
.httpBasic(Customizer.withDefaults());
|
||||
|
||||
|
|
|
@ -9,3 +9,7 @@ spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
|
|||
#spring.datasource.username=mysqluser
|
||||
#spring.datasource.password=mysqlpass
|
||||
#spring.datasource.url=jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true
|
||||
|
||||
# MultiTenantApplication
|
||||
defaultTenant=tenant_1
|
||||
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
|
Loading…
Reference in New Issue