Compare commits

..

22 Commits

Author SHA1 Message Date
d1a297b6b8 Update AbstractBaseEntity for fixing builder
Some checks failed
SNAPSHOT - Build and Publish Maven Artifacts / Run Sonarqube Tests (push) Has been cancelled
SNAPSHOT - Build and Publish Maven Artifacts / Build Java Package and Publish (push) Has been cancelled
2024-09-11 21:01:50 +10:00
94b638a2a5 Update AbstractBaseEntity for fixing builder 2024-09-11 20:45:05 +10:00
57e853788d remove profile hikari 2024-09-11 17:29:36 +10:00
605d80d8c9 update AbstractBaseEntity for common entity properties 2024-09-11 11:06:44 +10:00
04dd613e1e add AbstractBaseEntity for common entity properties 2024-09-10 17:42:05 +10:00
0e1364fa14 add AbstractBaseEntity for common entity properties 2024-09-10 17:41:47 +10:00
cefddb61e1 update security module 2024-09-10 17:21:09 +10:00
41102b7453 Merge pull request #5 from 3dwardch3ng/renovate/actions-setup-java-4.x
chore(deps): update actions/setup-java action to v4.3.0
2024-09-10 16:26:11 +10:00
renovate[bot]
3fa029b2d3 chore(deps): update actions/setup-java action to v4.3.0 2024-09-09 14:51:45 +00:00
badf9f7741 add module exception with WrongCredentialsException 2024-09-10 00:51:09 +10:00
4047ea5b9b fix groupId for ec-microservice-commons-swagger 2024-09-10 00:13:37 +10:00
ca9329b543 Merge pull request #4 from 3dwardch3ng/renovate/actions-cache-4.x
chore(deps): update actions/cache action to v4
2024-09-09 21:29:02 +10:00
renovate[bot]
910abdc14c chore(deps): update actions/cache action to v4 2024-09-09 11:21:13 +00:00
cadd18386a add GHA pipeline for sonarqube test 2024-09-09 21:20:37 +10:00
b7286c4928 add GHA pipeline for sonarqube test 2024-09-09 21:17:46 +10:00
92bb98fd16 Merge remote-tracking branch 'origin/develop' into develop 2024-09-09 21:08:35 +10:00
d7dade9e78 add GHA pipeline for sonarqube test 2024-09-09 21:08:29 +10:00
35868d40f2 Update for next development version [skip ci] 2024-09-09 10:42:42 +00:00
951bf56fe7 Merge tag '1.0.0' into develop
Tag release
2024-09-09 10:42:41 +00:00
ffd7f8a6b3 [RELEASE] 1.0.0 2024-09-09 10:42:41 +00:00
14fd4199e7 Update versions for release 2024-09-09 10:42:12 +00:00
5d92718924 Merge pull request #3 from 3dwardch3ng/develop
release
2024-09-09 20:41:30 +10:00
26 changed files with 545 additions and 16 deletions

View File

@@ -14,8 +14,74 @@ env:
RELEASE_DEPLOYMENT_REPOSITORY_URL: ${{ secrets.RELEASE_DEPLOYMENT_REPOSITORY_URL }} RELEASE_DEPLOYMENT_REPOSITORY_URL: ${{ secrets.RELEASE_DEPLOYMENT_REPOSITORY_URL }}
jobs: jobs:
sonarqube-test:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: write
packages: write
name: Run Sonarqube Tests
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- uses: actions/setup-java@v4.3.0
if: ${{ hashFiles('**/pom.xml') }}
with:
java-version: 17
distribution: zulu
cache: 'maven'
- name: Cache SonarQube packages
uses: actions/cache@v4
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Maven packages
uses: actions/cache@v4
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2
- name: maven-settings-xml-action
uses: whelk-io/maven-settings-xml-action@v22
with:
profiles: >
[{
"id": "homelab",
"properties": {
"altSnapshotDeploymentRepository": "nexus-snapshot::${env.SNAPSHOT_DEPLOYMENT_REPOSITORY_URL}",
"altReleaseDeploymentRepository": "nexus-release::${env.RELEASE_DEPLOYMENT_REPOSITORY_URL}"
}
}]
repositories: >
[{
"id": "maven-public",
"url": "${env.MAVEN_PUBLIC_REPOSITORY_URL}",
"snapshots": {
"enabled": "true"
}
}]
servers: >
[{
"id": "nexus-snapshot",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
},
{
"id": "nexus-release",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
}]
- name: Build and analyse
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=ec-microservice-commons -Dsonar.projectName='ec-microservice-commons' -P homelab
build-java: build-java:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs:
- sonarqube-test
permissions: permissions:
id-token: write id-token: write
contents: write contents: write
@@ -25,7 +91,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
- uses: actions/setup-java@v4.2.2 - uses: actions/setup-java@v4.3.0
if: ${{ hashFiles('**/pom.xml') }} if: ${{ hashFiles('**/pom.xml') }}
with: with:
java-version: 17 java-version: 17

View File

@@ -14,8 +14,74 @@ env:
RELEASE_DEPLOYMENT_REPOSITORY_URL: ${{ secrets.RELEASE_DEPLOYMENT_REPOSITORY_URL }} RELEASE_DEPLOYMENT_REPOSITORY_URL: ${{ secrets.RELEASE_DEPLOYMENT_REPOSITORY_URL }}
jobs: jobs:
sonarqube-test:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: write
packages: write
name: Run Sonarqube Tests
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- uses: actions/setup-java@v4.3.0
if: ${{ hashFiles('**/pom.xml') }}
with:
java-version: 17
distribution: zulu
cache: 'maven'
- name: Cache SonarQube packages
uses: actions/cache@v4
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Maven packages
uses: actions/cache@v4
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2
- name: maven-settings-xml-action
uses: whelk-io/maven-settings-xml-action@v22
with:
profiles: >
[{
"id": "homelab",
"properties": {
"altSnapshotDeploymentRepository": "nexus-snapshot::${env.SNAPSHOT_DEPLOYMENT_REPOSITORY_URL}",
"altReleaseDeploymentRepository": "nexus-release::${env.RELEASE_DEPLOYMENT_REPOSITORY_URL}"
}
}]
repositories: >
[{
"id": "maven-public",
"url": "${env.MAVEN_PUBLIC_REPOSITORY_URL}",
"snapshots": {
"enabled": "true"
}
}]
servers: >
[{
"id": "nexus-snapshot",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
},
{
"id": "nexus-release",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
}]
- name: Build and analyse
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=ec-microservice-commons -Dsonar.projectName='ec-microservice-commons' -P homelab
build-java: build-java:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs:
- sonarqube-test
permissions: permissions:
id-token: write id-token: write
contents: write contents: write
@@ -25,7 +91,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
- uses: actions/setup-java@v4.2.2 - uses: actions/setup-java@v4.3.0
if: ${{ hashFiles('**/pom.xml') }} if: ${{ hashFiles('**/pom.xml') }}
with: with:
java-version: 17 java-version: 17

71
.github/workflows/sonarqube.yaml vendored Normal file
View File

@@ -0,0 +1,71 @@
name: Build
on:
workflow_dispatch:
push:
branches:
- '!main'
- '!develop'
jobs:
build:
name: Build and analyze
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- uses: actions/setup-java@v4.3.0
if: ${{ hashFiles('**/pom.xml') }}
with:
java-version: 17
distribution: zulu
cache: 'maven'
- name: Cache SonarQube packages
uses: actions/cache@v4
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Maven packages
uses: actions/cache@v4
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2
- name: maven-settings-xml-action
uses: whelk-io/maven-settings-xml-action@v22
with:
profiles: >
[{
"id": "homelab",
"properties": {
"altSnapshotDeploymentRepository": "nexus-snapshot::${env.SNAPSHOT_DEPLOYMENT_REPOSITORY_URL}",
"altReleaseDeploymentRepository": "nexus-release::${env.RELEASE_DEPLOYMENT_REPOSITORY_URL}"
}
}]
repositories: >
[{
"id": "maven-public",
"url": "${env.MAVEN_PUBLIC_REPOSITORY_URL}",
"snapshots": {
"enabled": "true"
}
}]
servers: >
[{
"id": "nexus-snapshot",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
},
{
"id": "nexus-release",
"username": "${env.NEXUS_USERNAME}",
"password": "${env.NEXUS_PASSWORD}"
}]
- name: Build and analyze
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=ec-microservice-commons -Dsonar.projectName='ec-microservice-commons'

View File

@@ -6,7 +6,7 @@
<parent> <parent>
<groupId>sydney.cheng</groupId> <groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons</artifactId> <artifactId>ec-microservice-commons</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.1-SNAPSHOT</version>
</parent> </parent>
<artifactId>ec-microservice-commons-configuration</artifactId> <artifactId>ec-microservice-commons-configuration</artifactId>

View File

@@ -8,7 +8,7 @@ import org.springframework.context.annotation.Profile;
import java.io.Serializable; import java.io.Serializable;
import java.util.Properties; import java.util.Properties;
@Profile(value = {"database & hikari"}) @Profile(value = {"database"})
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@Data @Data
public class HikariDataSourceProperties extends HikariConfig implements Serializable { public class HikariDataSourceProperties extends HikariConfig implements Serializable {

View File

@@ -5,7 +5,7 @@ import org.springframework.context.annotation.Profile;
import java.util.Properties; import java.util.Properties;
@Profile(value = {"database & hikari"}) @Profile(value = {"database"})
@ConfigurationProperties("app.database.primary.datasource.hikari") @ConfigurationProperties("app.database.primary.datasource.hikari")
public class PrimaryHikariDataSourceProperties extends HikariDataSourceProperties { public class PrimaryHikariDataSourceProperties extends HikariDataSourceProperties {
public PrimaryHikariDataSourceProperties() { public PrimaryHikariDataSourceProperties() {

View File

@@ -5,7 +5,7 @@ import org.springframework.context.annotation.Profile;
import java.util.Properties; import java.util.Properties;
@Profile(value = {"database & hikari"}) @Profile(value = {"database"})
@ConfigurationProperties("app.database.replica.datasource.hikari") @ConfigurationProperties("app.database.replica.datasource.hikari")
public class ReplicaHikariDataSourceProperties extends HikariDataSourceProperties { public class ReplicaHikariDataSourceProperties extends HikariDataSourceProperties {
public ReplicaHikariDataSourceProperties() { public ReplicaHikariDataSourceProperties() {

View File

@@ -6,7 +6,7 @@
<parent> <parent>
<groupId>sydney.cheng</groupId> <groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons</artifactId> <artifactId>ec-microservice-commons</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.1-SNAPSHOT</version>
</parent> </parent>
<artifactId>ec-microservice-commons-database</artifactId> <artifactId>ec-microservice-commons-database</artifactId>

View File

@@ -15,7 +15,7 @@ import java.util.Map;
import static sydney.cheng.microservice.commons.database.constant.DatabaseBeanConstant.*; import static sydney.cheng.microservice.commons.database.constant.DatabaseBeanConstant.*;
@Profile(value = {"database & hikari"}) @Profile(value = {"database"})
@Getter @Getter
@Setter @Setter
@ToString @ToString

View File

@@ -21,7 +21,7 @@ import java.util.Map;
import static sydney.cheng.microservice.commons.database.constant.DatabaseBeanConstant.*; import static sydney.cheng.microservice.commons.database.constant.DatabaseBeanConstant.*;
@Profile(value = {"database & hikari"}) @Profile(value = {"database"})
@Configuration @Configuration
@EnableJpaRepositories( @EnableJpaRepositories(
basePackages = "sydney.cheng.**.repository", basePackages = "sydney.cheng.**.repository",

View File

@@ -6,7 +6,7 @@
<parent> <parent>
<groupId>sydney.cheng</groupId> <groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons</artifactId> <artifactId>ec-microservice-commons</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.1-SNAPSHOT</version>
</parent> </parent>
<artifactId>ec-microservice-commons-entity</artifactId> <artifactId>ec-microservice-commons-entity</artifactId>

View File

@@ -0,0 +1,29 @@
package sydney.cheng.microservice.commons.entity;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.hibernate.annotations.UuidGenerator;
import java.io.Serializable;
import java.time.LocalDateTime;
@MappedSuperclass
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AbstractBaseEntity implements Serializable {
@Id
@UuidGenerator(style = UuidGenerator.Style.TIME)
private String id;
@CreationTimestamp
private LocalDateTime creationTimestamp;
@UpdateTimestamp
private LocalDateTime updateTimestamp;
}

View File

@@ -1,4 +1,4 @@
package sydney.cheng.entity; package sydney.cheng.microservice.commons.entity;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;

26
exception/pom.xml Normal file
View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons</artifactId>
<version>1.0.1-SNAPSHOT</version>
</parent>
<artifactId>ec-microservice-commons-exceptions</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,11 @@
package sydney.cheng.microservice.commons.exceptions.auth;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public class WrongCredentialsException extends RuntimeException {
public WrongCredentialsException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,12 @@
package sydney.cheng.microservice.commons.exceptions.feign;
import lombok.Builder;
import lombok.Getter;
import java.util.Map;
@Builder
@Getter
public class FeignBadRequestException extends RuntimeException {
private Map<String, String> errors;
}

View File

@@ -0,0 +1,18 @@
package sydney.cheng.microservice.commons.exceptions.feign;
import lombok.Builder;
import lombok.Getter;
import org.springframework.http.HttpStatus;
@Builder
@Getter
public class FeignErrorException extends RuntimeException {
private final String message;
private final HttpStatus httpStatus;
public FeignErrorException(String message, HttpStatus httpStatus) {
super(message);
this.message = message;
this.httpStatus = httpStatus;
}
}

View File

@@ -0,0 +1,22 @@
package sydney.cheng.microservice.commons.exceptions.handlers;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import sydney.cheng.microservice.commons.exceptions.auth.WrongCredentialsException;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class AuthExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(WrongCredentialsException.class)
public ResponseEntity<?> usernameOrPasswordInvalidException(WrongCredentialsException exception) {
Map<String, String> errors = new HashMap<>();
errors.put("error", exception.getMessage());
return new ResponseEntity<>(errors, HttpStatus.UNAUTHORIZED);
}
}

View File

@@ -0,0 +1,26 @@
package sydney.cheng.microservice.commons.exceptions.handlers;
import sydney.cheng.microservice.commons.exceptions.feign.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class FeignExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(FeignErrorException.class)
public ResponseEntity<?> genericError(FeignErrorException exception) {
Map<String, String> errors = new HashMap<>();
errors.put("error", exception.getMessage());
return new ResponseEntity<>(errors, exception.getHttpStatus());
}
@ExceptionHandler(FeignBadRequestException.class)
public ResponseEntity<?> validationException(FeignBadRequestException exception) {
return ResponseEntity.badRequest().body(exception.getErrors());
}
}

View File

@@ -0,0 +1,21 @@
package sydney.cheng.microservice.commons.exceptions.handlers;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GenericExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<?> handleAllException(Exception ex) {
Map<String, String> errors = new HashMap<>();
errors.put("error", ex.getMessage());
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
}

View File

@@ -7,11 +7,11 @@
<parent> <parent>
<groupId>sydney.cheng</groupId> <groupId>sydney.cheng</groupId>
<artifactId>ec-super-pom</artifactId> <artifactId>ec-super-pom</artifactId>
<version>1.0.4</version> <version>1.0.5</version>
</parent> </parent>
<artifactId>ec-microservice-commons</artifactId> <artifactId>ec-microservice-commons</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.1-SNAPSHOT</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<licenses> <licenses>
@@ -43,6 +43,8 @@
<module>entity</module> <module>entity</module>
<module>configuration</module> <module>configuration</module>
<module>database</module> <module>database</module>
<module>exception</module>
<module>security</module>
</modules> </modules>
<properties> <properties>

44
security/pom.xml Normal file
View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons</artifactId>
<version>1.0.1-SNAPSHOT</version>
</parent>
<artifactId>ec-microservice-commons-security</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons-configuration</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons-exceptions</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,14 @@
package sydney.cheng.microservice.commons.security.config;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sydney.cheng.microservice.commons.security.utils.FeignErrorDecoder;
@Configuration
public class FeignConfig {
@Bean
public ErrorDecoder errorDecoder() {
return new FeignErrorDecoder();
}
}

View File

@@ -0,0 +1,60 @@
package sydney.cheng.microservice.commons.security.config;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import sydney.cheng.microservice.commons.configuration.properties.auth.CorsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig {
private final CorsProperties corsProperties;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.formLogin(AbstractHttpConfigurer::disable)
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
.authorizeHttpRequests(authorize ->
authorize
.requestMatchers(HttpMethod.OPTIONS, "*").permitAll()
.requestMatchers("/actuator/**",
"/swagger-ui/**", "/swagger-resources/**", "/api-docs/**",
"/config/**"
).permitAll()
.anyRequest().authenticated()
)
.exceptionHandling(exceptionHandling -> exceptionHandling.accessDeniedHandler(new AccessDeniedHandlerImpl()))
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(Customizer.withDefaults())
.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(corsProperties.isAllowCredentials());
corsConfiguration.setAllowedOrigins(corsProperties.getAllowedUrlList());
corsConfiguration.setAllowedHeaders(corsProperties.getAllowedHeaders());
corsConfiguration.setAllowedMethods(corsProperties.getAllowedMethods());
corsConfiguration.setMaxAge(corsProperties.getAllowedMaxAge());
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}
}

View File

@@ -0,0 +1,41 @@
package sydney.cheng.microservice.commons.security.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpStatus;
import sydney.cheng.microservice.commons.exceptions.feign.FeignBadRequestException;
import sydney.cheng.microservice.commons.exceptions.feign.FeignErrorException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class FeignErrorDecoder implements ErrorDecoder {
private final ObjectMapper mapper = new ObjectMapper();
@Override
public Exception decode(String methodKey, Response response) {
try (InputStream body = response.body().asInputStream()) {
Map<String, String> errors =
mapper.readValue(IOUtils.toString(body, StandardCharsets.UTF_8), Map.class);
if (response.status() == 400) {
return FeignBadRequestException.builder()
.errors(errors).build();
} else
return FeignErrorException
.builder()
.httpStatus(HttpStatus.valueOf(response.status()))
.message(errors.get("error"))
.build();
} catch (IOException exception) {
throw FeignErrorException.builder()
.httpStatus(HttpStatus.valueOf(response.status()))
.message(exception.getMessage())
.build();
}
}
}

View File

@@ -7,12 +7,12 @@
<parent> <parent>
<groupId>sydney.cheng</groupId> <groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons</artifactId> <artifactId>ec-microservice-commons</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.1-SNAPSHOT</version>
</parent> </parent>
<groupId>cheng.edward</groupId> <groupId>sydney.cheng</groupId>
<artifactId>ec-microservice-commons-swagger</artifactId> <artifactId>ec-microservice-commons-swagger</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.1-SNAPSHOT</version>
<properties> <properties>
<maven.compiler.source>17</maven.compiler.source> <maven.compiler.source>17</maven.compiler.source>