From e5501e1542e035b5708ac882003329e764f3ee26 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Mon, 17 Nov 2025 15:33:48 +0900 Subject: [PATCH] =?UTF-8?q?251117=5F02=5FENH=20:=20Security,=20Swagger,=20?= =?UTF-8?q?MVC=20=EA=B8=B0=EB=B3=B8=20=EC=84=A4=EC=A0=95=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 859 ++++++++++-------- build.gradle | 7 +- .../kri/common/security/ApiKeyAuthFilter.java | 69 ++ .../security/JwtAuthenticationFilter.java | 48 + .../KriSecurityAutoConfiguration.java | 87 ++ .../security/KriSecurityProperties.java | 28 + .../swagger/KriSwaggerAutoConfiguration.java | 70 ++ .../common/swagger/KriSwaggerProperties.java | 22 + .../webmvc/IpAccessControlInterceptor.java | 26 + .../common/webmvc/IpAccessControlService.java | 20 + .../java/com/kri/common/webmvc/IpUtil.java | 27 + .../common/webmvc/KriIpAccessProperties.java | 44 + .../webmvc/KriWebMvcAutoConfiguration.java | 63 ++ ...ot.autoconfigure.AutoConfiguration.imports | 5 +- 14 files changed, 995 insertions(+), 380 deletions(-) create mode 100644 src/main/java/com/kri/common/security/ApiKeyAuthFilter.java create mode 100644 src/main/java/com/kri/common/security/JwtAuthenticationFilter.java create mode 100644 src/main/java/com/kri/common/security/KriSecurityAutoConfiguration.java create mode 100644 src/main/java/com/kri/common/security/KriSecurityProperties.java create mode 100644 src/main/java/com/kri/common/swagger/KriSwaggerAutoConfiguration.java create mode 100644 src/main/java/com/kri/common/swagger/KriSwaggerProperties.java create mode 100644 src/main/java/com/kri/common/webmvc/IpAccessControlInterceptor.java create mode 100644 src/main/java/com/kri/common/webmvc/IpAccessControlService.java create mode 100644 src/main/java/com/kri/common/webmvc/IpUtil.java create mode 100644 src/main/java/com/kri/common/webmvc/KriIpAccessProperties.java create mode 100644 src/main/java/com/kri/common/webmvc/KriWebMvcAutoConfiguration.java diff --git a/README.md b/README.md index f46f2c3..30c7e73 100644 --- a/README.md +++ b/README.md @@ -3,243 +3,250 @@ Spring Boot 기반 사내 서비스에서 공통으로 사용하는 기능들을 모아둔 라이브러리입니다. `example-service` 같은 개별 서비스는 이 라이브러리를 통해 다음과 같은 기능을 **일관된 방식으로 재사용**할 수 있습니다. +- 공통 Security 자동 구성 (JWT + API Key, `com.kri.common.security`) - JWT 기반 인증/인가 (`com.kri.common.auth.jwt`) - 외부 API Key 인증 (`com.kri.common.auth.apikey`) -- 공통 Web 예외 처리 & 로깅 (`com.kri.common.web`) -- Redis 큐 헬퍼 (`com.kri.common.redis`) +- 공통 WebMvc 설정 (CORS + Swagger IP 접근 제어, `com.kri.common.web`) +- 공통 Web 예외 처리 & 로깅 (`ErrorAdvice`, `BusinessException`, MDC/Trace) +- Redis 큐 헬퍼 (`com.kri.common.redis.RedisQueueHelper`) - 스케줄링 활성화 (`com.kri.common.scheduling`) -- 기본 logback 설정 +- 기본 logback 설정 (`logback-spring.xml`) -이 문서는 **KriCommon을 사용하는 서비스(example-service)** 기준으로 작성되었습니다. +이 문서는 **KriCommon을 사용하는 서비스(`example-service`)** 기준으로 작성되었습니다. +(WebSocket 관련 기능은 현재 포함하지 않았으며, 추후 필요 시 별도 확장 예정입니다.) --- -## 1. 환경 요구사항 +## 1. 의존성 추가 -- **Java 17** -- **Spring Boot 3.5.x** - (KriCommon 내부 BOM: `org.springframework.boot:spring-boot-dependencies:3.5.7`) -- **Servlet 기반 Spring MVC** (WebFlux 미지원) - ---- - -## 2. 의존성 추가 - -### 2.1. Gitea Maven Registry 설정 +### 1.1. Gradle 예시 (권장) `example-service/build.gradle`: -```groovy +```gradle repositories { mavenCentral() + // Gitea 사내 Maven 레지스트리 + def giteaUser = findProperty("giteaUser") ?: "" + def giteaToken = findProperty("giteaToken") ?: "" + maven { name = "gitea" - url = uri("http://10.10.10.11:3000/api/packages/KRi/maven") - allowInsecureProtocol = true + url = uri("https://gitea.kric.com/api/packages/KRi/maven") credentials { - username = findProperty("giteaUser") ?: "" - password = findProperty("giteaToken") ?: "" + username = giteaUser + password = giteaToken } } } -``` -`gradle.properties` (루트 또는 사용자 홈): +dependencies { + // Spring Boot 기본 의존성 (서비스 쪽에서 직접 선언) + implementation "org.springframework.boot:spring-boot-starter-web" + implementation "org.springframework.boot:spring-boot-starter-security" + implementation "org.springframework.boot:spring-boot-starter-validation" + + // Swagger / OpenAPI UI + implementation "org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0" + + // (필요 시) Redis + implementation "org.springframework.boot:spring-boot-starter-data-redis" + + // KriCommon + implementation "com.kri.common:starter:1.0.11" +} +```` + +`~/.gradle/gradle.properties` (또는 프로젝트 `gradle.properties`)에 자격 증명: ```properties giteaUser=gitadmin -giteaToken=YOUR_GITEA_TOKEN # 실제 토큰으로 교체 +giteaToken=토큰값_여기에 ``` -> **Tip** -> - 토큰을 깃이나 공유 저장소에 올리지 않도록 주의하세요. -> - 실제로는 환경 변수 또는 CI/CD 시크릿을 사용해 주입하는 것을 권장합니다. - -### 2.2. Starter 라이브러리 의존성 - -```groovy -dependencies { - // 필수 Spring Boot 의존성 (예시) - implementation 'org.springframework.boot:spring-boot-starter-web' - implementation 'org.springframework.boot:spring-boot-starter-security' - implementation 'org.springframework.boot:spring-boot-starter-validation' - implementation 'org.springframework.boot:spring-boot-starter-aop' - implementation 'org.springframework.boot:spring-boot-starter-data-redis' - - // Swagger / OpenAPI (선택, 문서화용) - implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0' - - // ✅ KriCommon Starter - implementation 'com.kri.common:starter:1.0.1' -} -``` +> **주의** +> KriCommon은 `java-library` + `compileOnly` 위주로 구성되어 있어서 +> **웹/시큐리티/Swagger/Redis Starter는 개별 서비스에서 직접 의존성을 추가**해야 합니다. --- -## 3. 구성 요소 개요 +## 2. 자동 구성(AutoConfiguration) 개요 -KriCommon 은 크게 5가지 축으로 나뉩니다. +KriCommon은 다음 AutoConfiguration 들을 제공합니다. +모두 `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`에서 자동 등록됩니다. -1. **인증/인가** - - JWT, API Key를 모두 공통 DTO(`JwtUserClaimsDto`) 기반으로 정규화 -2. **Web 공통 기능** - - 예외 처리, traceId/MDC, AOP 기반 service/handler 로깅 -3. **Redis 큐 지원** - - 간단한 Redis List 기반 큐 컨슈머/프로듀서 유틸 -4. **스케줄링 활성화** - - 서비스에서 직접 `@EnableScheduling` 선언 없이 property 로 on/off -5. **로깅/Logback 기본 설정** - - traceId, service, handler, thread 정보가 통일된 패턴으로 출력 +| 클래스 | 역할 요약 | +| ------------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| `com.kri.common.auth.jwt.JwtAutoConfiguration` | `JwtProperties`, `ApiKeyProperties` 바인딩 + `JwtService`, `ApiKeyAuthFilter` 자동 Bean 생성 | +| `com.kri.common.security.KriSecurityAutoConfiguration` | SecurityFilterChain 기본 구성(JWT + API Key 필터) + `@EnableMethodSecurity` | +| `com.kri.common.web.CommonWebAutoConfiguration` | 공통 예외 처리(`ErrorAdvice`), `TraceFilter` 등록 | +| `com.kri.common.web.KriWebMvcAutoConfiguration` | CORS 기본 설정 + Swagger IP 접근 제어 Interceptor 등록 | +| `com.kri.common.swagger.KriSwaggerAutoConfiguration` | OpenAPI/Swagger 기본 설정 + JWT/API-Key SecurityScheme 등록 | +| `com.kri.common.redis.CommonRedisAutoConfiguration` | `StringRedisTemplate`, `RedisQueueHelper` 자동 구성 (`RedisConnectionFactory` 존재 시) | +| `com.kri.common.scheduling.CommonSchedulingAutoConfiguration` | `@EnableScheduling` 자동 활성화 | -각 기능은 **프로퍼티 + AutoConfiguration + 유틸 Bean** 조합으로 제공되며, -서비스는 필요한 부분만 선택적으로 활성화하면 됩니다. +각 AutoConfiguration은 **프로퍼티로 on/off 가능**하며, 필요 시 서비스 쪽에서 Bean을 직접 정의하여 오버라이드 할 수 있습니다. --- -## 4. 설정 예시 (application.yml) +## 3. application.yml 예시 -`example-service/src/main/resources/application.yml` 기본 예시는 다음과 같습니다. +`example-service/src/main/resources/application.yml`: ```yaml -server: - port: 8080 - spring: application: name: example-service + datasource: + # (서비스에서 실제 DB 설정) + + # Redis 사용 시 (선택) + data: + redis: + host: localhost + port: 6379 + +server: + port: 8080 + logging: file: - path: ./logs + path: logs + level: + root: INFO + com.kri: DEBUG +# =========================== +# KRI 공통 설정 +# =========================== kri: auth: jwt: - secret: "CHANGE_ME_TO_A_SECURE_SECRET_32+CHARS" + secret: "서비스별_실제_시크릿키_32자_이상" issuer: "kri-it" - - # 내부 시스템 간 통신에 사용할 고정 토큰 (선택) - internal-fixed-token: "VERY_SECURE_INTERNAL_TOKEN_VALUE" - - # 고정 토큰 사용 시 SecurityContext 에 올릴 기본 계정정보 - internal-user-id: "SYSTEM_EXAMPLE" - internal-user-team: "IT" - internal-user-name: "Example Internal System" - internal-user-role: 999 - + access-token-validity-seconds: 86400 # 24시간 + refresh-token-validity-seconds: 604800 # 7일 apikey: - enabled: true # API Key 인증 사용 여부 - header-name: "X-API-Key" # API Key 헤더 이름 + enabled: true # 외부 API Key 인증 사용 여부 + header-name: "X-API-Key" # API Key 헤더 이름 + + security: + enabled: true + # 인증 없이 허용할 URL 패턴들 (기본값 + 필요시 추가/override) + public-paths: + - "/v3/api-docs/**" + - "/swagger-ui.html" + - "/swagger-ui/**" + - "/actuator/health" + + swagger: + enabled: true + title: "Example Service API" + description: "Example Service OpenAPI Docs" + version: "v1" + base-package: "com.kri.example.api" + + webmvc: + enabled: true + ip: + # 기본 CIDR(로컬 + 사내 대역)은 라이브러리 내부에 정의되어 있음 + # 여기서는 *추가* CIDR만 설정 (기본값은 그대로 유지) + additional-cidrs: + - "10.10.0.0/16" + - "192.168.0.0/16" common: web: - enabled: true # 공통 Web 구성 사용 여부 (기본 true) + enabled: true # ErrorAdvice + TraceFilter redis: - enabled: false # RedisQueueHelper 사용 시 true + enabled: false # RedisQueueHelper (필요 시 true) scheduling: - enabled: false # @Scheduled 사용 시 true + enabled: false # @EnableScheduling (필요 시 true) ``` -### 4.1. `kri.auth.jwt` 속성 요약 - -| 프로퍼티 | 타입 | 기본값 | 설명 | -| ---------------------------------------- | -------- | ---------------------------------- | ---- | -| `kri.auth.jwt.secret` | String | (기본값 있음, 서비스에서 override 권장) | HMAC 서명에 사용할 시크릿 키 (최소 32자 이상) | -| `kri.auth.jwt.issuer` | String | `"kri-it"` | 토큰 발급자(issuer) | -| `kri.auth.jwt.access-token-validity-seconds` | long | `24 * 3600` | Access Token 유효 시간(초) | -| `kri.auth.jwt.refresh-token-validity-seconds` | long | `7 * 24 * 3600` | Refresh Token 유효 시간(초) | - -### 4.2. `kri.auth.apikey` 속성 요약 - -| 프로퍼티 | 타입 | 기본값 | 설명 | -| ------------------------------ | ------- | ---------- | ---- | -| `kri.auth.apikey.enabled` | boolean | `false` | API Key 인증 기능 활성화 여부 | -| `kri.auth.apikey.header-name` | String | `X-API-Key`| API Key 를 읽을 HTTP 헤더 이름 | - -### 4.3. `common.*` 속성 요약 - -| 프로퍼티 | 타입 | 기본값 | 설명 | -| -------------------------- | ------- | ------ | ---- | -| `common.web.enabled` | boolean | `true` | Web 예외/로깅/필터 자동 구성 여부 | -| `common.redis.enabled` | boolean | `false`| RedisQueueHelper 자동 구성 여부 | -| `common.scheduling.enabled`| boolean | `false`| `@EnableScheduling` 자동 적용 여부 | - --- -## 5. JWT 기능 상세 (`com.kri.common.auth.jwt`) +## 4. 주요 기능 상세 -### 5.1. JwtUserClaimsDto +### 4.1. JWT 설정 및 DTO (`com.kri.common.auth.jwt`) -JWT 에 들어가는 **표준 Payload** 를 정의하는 DTO입니다. +#### 4.1.1. JwtProperties ```java -@Schema( - name = "JwtUserClaimsDto", - description = "JWT에 포함되는 사용자 정보 (T_USER 기준)" -) +@ConfigurationProperties(prefix = "kri.auth.jwt") +public class JwtProperties { + private String secret; // HMAC 시크릿 키 (기본값 존재, 서비스에서 override 권장) + private String issuer = "kri-it"; + private long accessTokenValiditySeconds = 24 * 3600; + private long refreshTokenValiditySeconds = 7 * 24 * 3600; +} +``` + +**프로퍼티 요약** + +| 프로퍼티 | 타입 | 기본값 | 설명 | +| --------------------------------------------- | ------ | ------------ | -------------------------------------- | +| `kri.auth.jwt.secret` | String | (기본값 있음) | HMAC 서명용 시크릿(최소 32자 이상, 서비스별로 꼭 변경 추천) | +| `kri.auth.jwt.issuer` | String | `kri-it` | 토큰 발급자 | +| `kri.auth.jwt.access-token-validity-seconds` | long | 86,400 (24h) | Access Token 만료(초) | +| `kri.auth.jwt.refresh-token-validity-seconds` | long | 604,800 (7일) | Refresh Token 만료(초) | + +#### 4.1.2. JwtUserClaimsDto + +```java +package com.kri.common.auth.jwt; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Builder; +import lombok.Value; + @Value @Builder +@Schema(description = "JWT에 담기는 공통 사용자 정보") public class JwtUserClaimsDto { - @Schema(description = "사용자 ID (T_USER.USER_ID)") + @Schema(description = "사용자 ID (사내 시스템 기준 PK)", example = "user123") String userId; - @Schema(description = "팀 코드 또는 팀명 (T_USER.USER_TEAM)") + @Schema(description = "사용자 팀/조직명", example = "IT팀") String userTeam; - @Schema(description = "사용자 이름 (T_USER.USER_NM)") + @Schema(description = "사용자 이름", example = "홍길동") String userName; - @Schema(description = "권한 코드 (T_USER.ROLL, INTEGER)") + @Schema(description = "권한 레벨 (int)", example = "1") Integer role; } ``` -> Swagger/OpenAPI 를 사용하는 서비스에서는 -> 이 DTO를 반환 타입이나 요청 타입에 사용하면 자동으로 문서화됩니다. +> `@Schema`가 붙어 있어서, Swagger UI 상에서도 필드 설명이 자연스럽게 노출됩니다. -### 5.2. JwtService 주요 메서드 +#### 4.1.3. JwtService -JwtService 는 다음과 같은 역할을 합니다. - -1. **Access Token 발급** -2. **Refresh Token 발급** -3. **토큰 파싱 및 검증** -4. **토큰 → JwtUserClaimsDto/Authentication 변환** - -핵심 메서드 요약: +주요 메서드: ```java public class JwtService { - // Access Token 생성 + // Access Token 생성 (DTO → JWT 문자열) public String generateAccessToken(JwtUserClaimsDto userClaims); - // Refresh Token 생성 (subject = userId) + // Refresh Token 생성 public String generateRefreshToken(String userId); - // 토큰 파싱 + 서명/만료 검증 - public Jws parseToken(String token) throws JwtException; - - // Claims 추출 + // 토큰 파싱 & 검증 public Claims getClaims(String token) throws JwtException; - - // Claims -> DTO - public JwtUserClaimsDto toUserClaimsDto(Claims claims); - - // 토큰 -> DTO public JwtUserClaimsDto toUserClaimsDto(String token) throws JwtException; - // DTO -> Authentication (Spring Security) + // Spring Security Authentication 변환 public Authentication toAuthentication(JwtUserClaimsDto dto); - - // 토큰 -> Authentication public Authentication toAuthentication(String token) throws JwtException; } ``` -### 5.3. 로그인 흐름 예시 +**로그인 예시** ```java @Service @@ -248,85 +255,44 @@ public class AuthService { private final JwtService jwtService; - public String login(String userId, String password) { - // 1) userId/password 검증 및 T_USER 조회 - // 예시용 더미 값 - String userTeam = "TEAM_A"; - String userName = "홍길동"; - Integer role = 1; - + public String login(String username, String password) { + // 1) 서비스에서 사용자 검증 (DB 조회 등) + // 2) 검증 성공 시 공통 DTO 구성 JwtUserClaimsDto claims = JwtUserClaimsDto.builder() - .userId(userId) - .userTeam(userTeam) - .userName(userName) - .role(role) + .userId(username) + .userTeam("IT팀") + .userName("홍길동") + .role(1) // 권한 레벨 .build(); - // 2) Access Token 발급 + // 3) Access Token 발급 return jwtService.generateAccessToken(claims); } } ``` -### 5.4. JWT 인증 필터 예시 (서비스 측 구현) +--- -KriCommon 은 **JwtAuthenticationFilter 구현은 제공하지 않습니다.** -서비스마다 요구사항이 다르기 때문에, -아래와 같이 `JwtService` 를 사용하는 커스텀 필터를 작성해 연결하는 방식을 권장합니다. +### 4.2. API Key 인증 (`com.kri.common.auth.apikey`) + +#### 4.2.1. ApiKeyProperties ```java -@RequiredArgsConstructor -public class JwtAuthenticationFilter extends OncePerRequestFilter { - - private final JwtService jwtService; - - @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, - FilterChain filterChain) - throws ServletException, IOException { - - if (SecurityContextHolder.getContext().getAuthentication() == null) { - String header = request.getHeader("Authorization"); - if (header != null && header.startsWith("Bearer ")) { - String token = header.substring("Bearer ".length()); - - Authentication auth; - if (jwtService.isInternalFixedToken(token)) { - auth = jwtService.createInternalAuthentication(); - } else { - auth = jwtService.toAuthentication(token); - } - - SecurityContextHolder.getContext().setAuthentication(auth); - } - } - - filterChain.doFilter(request, response); - } +@ConfigurationProperties(prefix = "kri.auth.apikey") +public class ApiKeyProperties { + private boolean enabled = false; + private String headerName = "X-API-Key"; } ``` -SecurityConfig 에 등록: +**프로퍼티 요약** -```java -http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); -``` +| 프로퍼티 | 타입 | 기본값 | 설명 | +| ----------------------------- | ------- | ----------- | ----------------------- | +| `kri.auth.apikey.enabled` | boolean | `false` | API Key 인증 기능 사용 여부 | +| `kri.auth.apikey.header-name` | String | `X-API-Key` | API Key 를 읽을 HTTP 헤더 이름 | ---- - -## 6. API Key 인증 (`com.kri.common.auth.apikey`) - -### 6.1. 설계 개요 - -- 외부 시스템에서 발급한 API Key가 `X-API-Key` 헤더로 들어오는 경우를 처리하기 위한 기능입니다. -- KriCommon 은: - - 헤더에서 Key를 읽고 - - `ApiKeyUserClaimsProvider` 에 Key를 전달하여 - - 유효한 경우 `JwtUserClaimsDto` → `Authentication` 을 생성해 SecurityContext에 세팅합니다. -- 각 서비스는 **오직 "이 Key가 누구 것인지"만 구현**하면 됩니다. - -### 6.2. ApiKeyUserClaimsProvider (서비스에서 구현) +#### 4.2.2. ApiKeyUserClaimsProvider (서비스 구현 필요) ```java public interface ApiKeyUserClaimsProvider { @@ -341,25 +307,24 @@ public interface ApiKeyUserClaimsProvider { } ``` -구현 예시: +**서비스 구현 예시 (`example-service`)** ```java -@Service +@Component @RequiredArgsConstructor -public class ApiKeyUserClaimsProviderImpl implements ApiKeyUserClaimsProvider { - - // private final ApiKeyMapper apiKeyMapper; +public class ExampleApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider { @Override public Optional findUserByApiKey(String apiKey) { - // TODO: DB 조회(MyBatis)로 교체 - if ("EXTERNAL_KEY_1".equals(apiKey)) { + // 1) 사내 외부 파트너용 API Key 테이블 조회 + // 2) 유효하면 JwtUserClaimsDto 로 매핑 + if ("DEMO-KEY-1234".equals(apiKey)) { return Optional.of( JwtUserClaimsDto.builder() - .userId("partnerA") - .userTeam("EXT") - .userName("외부 파트너 A") - .role(10) + .userId("external-partner") + .userTeam("External") + .userName("외부 파트너") + .role(9) .build() ); } @@ -368,136 +333,325 @@ public class ApiKeyUserClaimsProviderImpl implements ApiKeyUserClaimsProvider { } ``` -### 6.3. ApiKeyAuthFilter (공통 필터) +#### 4.2.3. ApiKeyAuthFilter -KriCommon 에서 제공하는 필터는 다음과 같이 동작합니다. +`X-API-Key`(또는 설정된 헤더)로부터 API Key를 읽고, +`ApiKeyUserClaimsProvider`를 통해 사용자 정보를 조회한 뒤, `JwtService`를 사용해 `Authentication`을 세팅하는 필터입니다. -1. `kri.auth.apikey.enabled=false` 이면 아무 작업도 하지 않음 -2. 이미 SecurityContext에 Authentication 이 있으면 패스 -3. 설정된 헤더(`kri.auth.apikey.header-name`)에서 Key를 읽음 -4. `ApiKeyUserClaimsProvider` 로 조회 -5. DTO가 반환되면 `JwtService.toAuthentication(dto)`로 Authentication 생성 +> 이 필터는 `JwtAutoConfiguration` / `KriSecurityAutoConfiguration`를 통해 **자동 Bean 등록**되고, +> `SecurityFilterChain`에서 JWT 필터보다 먼저 동작하도록 설정됩니다. -서비스 측에서는 단지 **필터를 SecurityConfig 에 추가**하면 됩니다. +--- + +### 4.3. Security 기본 구성 (`com.kri.common.security`) + +#### 4.3.1. KriSecurityProperties ```java -@Configuration -@EnableWebSecurity -@RequiredArgsConstructor -public class SecurityConfig { +@ConfigurationProperties(prefix = "kri.security") +public class KriSecurityProperties { - private final ApiKeyAuthFilter apiKeyAuthFilter; + private boolean enabled = true; + + // 인증 없이 허용할 URL 패턴들 + private List publicPaths = List.of( + "/v3/api-docs/**", + "/swagger-ui.html", + "/swagger-ui/**" + ); +} +``` + +**프로퍼티 요약** + +| 프로퍼티 | 타입 | 기본값 (일부) | 설명 | +| --------------------------- | ------------ | ---------------- | -------------------------- | +| `kri.security.enabled` | boolean | `true` | 공통 Security 자동 구성 사용 여부 | +| `kri.security.public-paths` | List | Swagger 관련 패턴 포함 | `permitAll()` 로 열어둘 URL 목록 | + +서비스에서 Swagger 외에 `/actuator/health` 같은 것들도 열고 싶다면: + +```yaml +kri: + security: + public-paths: + - "/v3/api-docs/**" + - "/swagger-ui.html" + - "/swagger-ui/**" + - "/actuator/health" + - "/auth/login" +``` + +#### 4.3.2. KriSecurityAutoConfiguration + +특징: + +* `@AutoConfiguration(before = SecurityAutoConfiguration.class)` +* `@EnableMethodSecurity(jsr250Enabled = true, prePostEnabled = true)` +* `SecurityFilterChain` 기본 구성: + + * `httpBasic().disable()` + * `formLogin().disable()` + * `csrf().disable()` + * `cors(Customizer.withDefaults())` + * `SessionCreationPolicy.STATELESS` + * `public-paths` 는 `permitAll()`, 나머지는 `authenticated()` + * `ApiKeyAuthFilter` → `JwtAuthenticationFilter` 순으로 필터 체인에 추가 + +**메소드 레벨 권한 예시** + +```java +@RestController +@RequestMapping("/api/example") +public class ExampleController { + + // 누구나 접근 가능하게 열고 싶다면: + @jakarta.annotation.security.PermitAll + @GetMapping("/public") + public String publicApi() { ... } + + // 특정 권한 레벨 사용 (예: ROLE_1) + @org.springframework.security.access.prepost.PreAuthorize("hasRole('1')") + @GetMapping("/admin-only") + public String adminOnly() { ... } +} +``` + +> `@PermitAll` / `@PreAuthorize` 사용이 가능하며, +> URL 패턴 기반 예외 처리는 `kri.security.public-paths` 로 관리합니다. + +--- + +### 4.4. Swagger / OpenAPI (`com.kri.common.swagger`) + +#### 4.4.1. KriSwaggerProperties + +```java +@ConfigurationProperties(prefix = "kri.swagger") +public class KriSwaggerProperties { + private boolean enabled = true; + private String title = "KRI API"; + private String description = "KRI Common API Docs"; + private String version = "v1"; + private String basePackage; // 문서화할 base package (null 이면 전체) +} +``` + +#### 4.4.2. KriSwaggerAutoConfiguration + +* `OpenAPI` Bean을 생성하며, `Info(title, description, version)` 설정 +* `GroupedOpenApi` Bean 생성 + + * `group = "kri-api"` + * `basePackage` 가 설정되어 있으면 해당 패키지만 스캔 +* Swagger Security 설정: + + * HTTP Bearer JWT (`BearerAuth`) + * API Key 스키마 (`ApiKeyAuth`) — `kri.auth.apikey.enabled=true` 일 때 등록 + * 전역 `SecurityRequirement` 추가 → Swagger UI "Authorize" 버튼에 노출 + +서비스에서 필요한 것은: + +```gradle +dependencies { + implementation "org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0" + implementation "com.kri.common:starter:1.0.11" +} +``` + +그리고 `application.yml`에: + +```yaml +kri: + swagger: + enabled: true + title: "Example Service API" + description: "example-service OpenAPI Docs" + version: "v1" + base-package: "com.kri.example.api" +``` + +이렇게 하면 Swagger UI에서 **JWT / API Key 입력 후 전체 API에 공통으로 헤더가 붙는 형태**로 동작합니다. + +--- + +### 4.5. WebMvc + IP 접근 제어 (`com.kri.common.web`) + +#### 4.5.1. KriWebMvcAutoConfiguration + +```java +@AutoConfiguration +@EnableConfigurationProperties(KriIpAccessProperties.class) +@ConditionalOnProperty(prefix = "kri.webmvc", name = "enabled", havingValue = "true", matchIfMissing = true) +@RequiredArgsConstructor +public class KriWebMvcAutoConfiguration { @Bean - public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { - http - .csrf(csrf -> csrf.disable()) - .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) - .authorizeHttpRequests(auth -> auth - .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/actuator/health").permitAll() - .anyRequest().authenticated() - ); + @ConditionalOnMissingBean + public IpAccessControlService ipAccessControlService(KriIpAccessProperties props) { + return new IpAccessControlService(props); + } - // JWT 필터가 있다면 순서 조정 가능 - http.addFilterBefore(apiKeyAuthFilter, UsernamePasswordAuthenticationFilter.class); + @Bean + @ConditionalOnMissingBean + public IpAccessControlInterceptor ipAccessControlInterceptor(IpAccessControlService svc) { + return new IpAccessControlInterceptor(svc); + } - return http.build(); + @Bean + public WebMvcConfigurer kriWebMvcConfigurer(ObjectProvider ipAccessControlInterceptorProvider) { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOriginPatterns("*") + .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS") + .allowedHeaders("*") + .allowCredentials(true); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + ipAccessControlInterceptorProvider.ifAvailable(interceptor -> + registry.addInterceptor(interceptor) + .order(1) + .addPathPatterns("/swagger-ui/**", "/v3/api-docs/**") + ); + } + }; } } ``` ---- - -## 7. Web 공통 기능 (`com.kri.common.web`) - -### 7.1. ErrorAdvice & BusinessException - -- `BusinessException` 은 비즈니스 로직에서 발생시키는 커스텀 예외입니다. -- `ErrorAdvice` 가 이를 캐치하여 **`ProblemDetail` 기반 JSON 응답**으로 변환합니다. - -사용 예: +#### 4.5.2. KriIpAccessProperties & IP 설정 ```java -if (!true) { - throw BusinessException.of( - HttpStatus.BAD_REQUEST, - "INVALID_PARAM", - "요청 파라미터가 유효하지 않습니다." - ).with("field", "name"); +@ConfigurationProperties(prefix = "kri.webmvc.ip") +public class KriIpAccessProperties { + + private final List defaultCidrs = List.of( + "127.0.0.1/32", + "::1/128", + "1.235.195.0/24", + "211.254.145.128/25", + "175.45.203.213/32" + ); + + private List additionalCidrs = new ArrayList<>(); + + public List getEffectiveCidrs() { + return Stream.concat(defaultCidrs.stream(), additionalCidrs.stream()) + .distinct() + .collect(Collectors.toList()); + } } ``` -응답 예 (대략적인 형태): +**프로퍼티 요약** -```json -{ - "status": 400, - "title": "INVALID_PARAM", - "detail": "요청 파라미터가 유효하지 않습니다.", - "field": "name", - "traceId": "c5b2b6ab...", - "timestamp": "2025-01-01T12:34:56.789+09:00" +| 프로퍼티 | 타입 | 설명 | +| -------------------------------- | ------------ | --------------------------------- | +| `kri.webmvc.enabled` | boolean | CORS 및 Swagger IP 제어 자동 구성 on/off | +| `kri.webmvc.ip.additional-cidrs` | List | 기본 CIDR 목록에 *추가*할 CIDR 리스트 | + +예시: + +```yaml +kri: + webmvc: + enabled: true + ip: + additional-cidrs: + - "10.10.0.0/16" + - "192.168.0.0/16" +``` + +> 기본 CIDR(127.0.0.1, ::1, 사내 대역 등)은 라이브러리 안에 고정되어 있고, +> 서비스에서는 **추가 CIDR만** 설정하면 됩니다. + +#### 4.5.3. CommonWebAutoConfiguration + +```java +@AutoConfiguration +@ConditionalOnProperty(name = "common.web.enabled", matchIfMissing = true) +public class CommonWebAutoConfiguration { + + @Bean + public ErrorAdvice errorAdvice() { ... } + + @Bean + public FilterRegistrationBean traceFilter() { ... } } ``` -> 실제 필드 구조는 `ErrorAdvice` 구현을 참고하십시오. - -### 7.2. TraceFilter / MDC - -- `TraceFilter` - - 요청마다 `traceId` 를 생성 또는 `X-Request-Id` 헤더에서 재사용 - - MDC 에 `traceId` 세팅 -- `MdcHandlerConfig` - - HandlerInterceptor 를 사용해 `handler` 정보를 MDC에 기록 (`Controller#method`) -- `ServiceMdcAspect` - - `@Service` 메서드 호출 시 `service` MDC 필드에 기록 (`Service#method`) - -이 정보는 기본 logback 패턴(또는 서비스에서 override한 패턴)에 포함되어 -로그 상에서 **요청 단위/메서드 단위 추적**을 쉽게 만들 수 있습니다. +* `ErrorAdvice`: `@RestControllerAdvice` 형태의 글로벌 예외 처리 +* `TraceFilter`: HTTP 요청마다 `X-Request-Id` 및 MDC `traceId` 설정 +* 추가로 MDC 핸들러/Service AOP를 통해 로그에 handler/service 정보 포함 --- -## 8. Redis 큐 (`com.kri.common.redis`) +### 4.6. Redis 큐 (`com.kri.common.redis`) -### 8.1. 활성화 조건 +#### 4.6.1. CommonRedisAutoConfiguration -- `common.redis.enabled=true` -- `RedisConnectionFactory` Bean 이 존재 - (보통 `spring-boot-starter-data-redis` + `spring.data.redis.*` 설정) +```java +@AutoConfiguration +@ConditionalOnClass(RedisTemplate.class) +@ConditionalOnProperty(prefix = "common.redis", name = "enabled", havingValue = "true") +@ConditionalOnBean(RedisConnectionFactory.class) +public class CommonRedisAutoConfiguration { -> 두 조건이 충족되면 `CommonRedisAutoConfiguration` 이 -> `StringRedisTemplate` 및 `RedisQueueHelper` 를 자동으로 등록합니다. + @Bean @ConditionalOnMissingBean + public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory cf) { ... } -### 8.2. RedisQueueHelper 사용 예시 + @Bean @ConditionalOnMissingBean + public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) { ... } +} +``` + +**프로퍼티** + +| 프로퍼티 | 타입 | 기본값 | 설명 | +| ---------------------- | ------- | ----- | ---------------------- | +| `common.redis.enabled` | boolean | false | RedisQueueHelper 사용 여부 | + +#### 4.6.2. RedisQueueHelper 사용 예시 ```java @Service @RequiredArgsConstructor -public class JobQueueService { +public class ExportQueueService { private final RedisQueueHelper redisQueueHelper; - public void enqueueJob(String jobId) { - redisQueueHelper.enqueue("job-queue", jobId); + public void pushJob(String jobJson) { + redisQueueHelper.push("export:jobs", jobJson); } - public String dequeueJob() { - // 최대 5초 동안 대기 - return redisQueueHelper.blockingDequeue("job-queue", Duration.ofSeconds(5)); + public String popJob() { + return redisQueueHelper.pop("export:jobs"); } } ``` -**권장 패턴** - -- Producer: 서비스/컨트롤러에서 업무 이벤트를 큐에 적재 -- Consumer: @Scheduled 또는 별도 Thread에서 blockingDequeue 로 작업 수행 - --- -## 9. 스케줄링 (`com.kri.common.scheduling`) +### 4.7. 스케줄링 (`com.kri.common.scheduling`) -### 9.1. 활성화 방법 +```java +@AutoConfiguration +@EnableScheduling +@ConditionalOnProperty(prefix = "common.scheduling", name = "enabled", havingValue = "true") +public class CommonSchedulingAutoConfiguration { } +``` + +**프로퍼티** + +| 프로퍼티 | 타입 | 기본값 | 설명 | +| --------------------------- | ------- | ----- | -------------------------- | +| `common.scheduling.enabled` | boolean | false | `@EnableScheduling` 활성화 여부 | + +서비스 쪽에서는 단순히: ```yaml common: @@ -505,100 +659,49 @@ common: enabled: true ``` -이 설정만 켜면: - -- `CommonSchedulingAutoConfiguration` 이 `@EnableScheduling` 을 적용합니다. -- 서비스 코드에서는 평소처럼 `@Scheduled` 만 선언하면 됩니다. - -예: - -```java -@Component -public class ExampleScheduler { - - @Scheduled(fixedDelay = 10_000) - public void doSomething() { - // 10초마다 실행 - } -} -``` - -> 장점: -> - 서비스마다 `@EnableScheduling` 애노테이션 중복 선언을 피할 수 있음 -> - 프로퍼티로 스케줄링 on/off 제어가 쉬워짐 +만 지정하면, `@Scheduled` 애노테이션을 사용할 수 있습니다. --- -## 10. 로깅 / logback +### 4.8. 로그 설정 (`logback-spring.xml`) -KriCommon 은 기본적인 `logback-spring.xml` 을 제공합니다. +* `app.name` (없으면 기본값 `app`) +* `logging.file.path` (없으면 `logs`) -- 콘솔 로그 + 파일 로그(rolling) -- MDC 값 포함: - - `traceId` - - `handler` (Controller 메서드) - - `service` (Service 메서드) - - thread, level, logger 등 +을 활용해서 로그 디렉토리와 패턴을 설정합니다. -서비스에서 **직접 `logback-spring.xml` 을 제공하면 해당 설정이 우선 적용**되므로, -필요하면 KriCommon의 설정을 복사 후 서비스에 맞게 수정해서 사용하는 것을 권장합니다. +`traceId`, `handler`, `service` 등 MDC 정보가 포함된 공통 패턴을 사용하도록 되어 있으며, +서비스에서 별도의 `logback-spring.xml`을 두면 그 설정이 우선합니다. --- -## 11. Swagger / OpenAPI +## 5. example-service 적용 요약 -KriCommon 의 일부 DTO(`JwtUserClaimsDto` 등)에는 -`io.swagger.v3.oas.annotations.media.Schema` 어노테이션이 포함되어 있습니다. +1. **의존성 추가** -`example-service` 에서 springdoc-openapi 를 사용한다면, -다음과 같이 사용할 수 있습니다. + * Spring Boot Web / Security / Validation / (필요시) Redis / Swagger + * `implementation "com.kri.common:starter:1.0.11"` -```java -@RestController -public class MeController { +2. **application.yml 구성** - @Operation(summary = "현재 로그인 사용자 정보 조회") - @GetMapping("/api/me") - public JwtUserClaimsDto me() { - return JwtUserClaimsDto.builder() - .userId("demo") - .userTeam("TEAM") - .userName("데모 사용자") - .role(1) - .build(); - } -} -``` + * `kri.auth.jwt.*` : 시크릿/만료시간 설정 + * `kri.auth.apikey.*` : API Key 사용 여부 및 헤더 이름 + * `kri.security.public-paths` : 로그인/헬스체크/Swagger 등 열어둘 URL 설정 + * `kri.swagger.*` : title/description/base-package 설정 + * `kri.webmvc.ip.additional-cidrs` : Swagger 접근 허용 IP 대역 추가 + * `common.redis.enabled`, `common.scheduling.enabled` 등 필요 시 on -Swagger UI 에서: +3. **로그인 엔드포인트 구현** -- DTO 이름: `JwtUserClaimsDto` -- 각 필드별 설명: `@Schema(description = "...")` 내용이 그대로 노출됩니다. + * 사용자 검증 후 `JwtUserClaimsDto`를 만들어 `JwtService.generateAccessToken()` 호출 + * Controller에서 JWT를 응답으로 내려줌 ---- +4. **외부 API Key 사용 시** -## 12. 신규 서비스 적용 체크리스트 + * `ApiKeyUserClaimsProvider` 구현체를 Bean으로 등록 + * `kri.auth.apikey.enabled=true` 설정 -`example-service` 같은 신규 서비스에서 KriCommon 을 사용할 때, -다음 순서대로 점검하면 됩니다. +5. **권한 제어** -1. **Gradle 설정** - - Gitea Maven registry 추가 - - `implementation 'com.kri.common:starter:1.0.1'` 추가 -2. **application.yml** - - `kri.auth.jwt.secret` 최소 32자 이상으로 설정 - - 필요 시 `internal-fixed-token` 및 내부 계정 정보 설정 - - API Key 인증이 필요하면 `kri.auth.apikey.enabled=true` 및 header-name 지정 - - Web/Redis/Scheduling 사용 여부에 따라 `common.*` 설정 -3. **SecurityConfig** - - `ApiKeyAuthFilter` (공통) 필터 체인에 추가 - - JWT 인증이 필요하면 `JwtService` 기반 커스텀 JwtAuthenticationFilter 구현 후 추가 -4. **ApiKeyUserClaimsProvider 구현** - - DB/설정 파일 등에서 API Key → JwtUserClaimsDto 매핑 로직 작성 -5. **로그/예외 확인** - - 의도한 형태로 ProblemDetail, traceId, service/handler 로그가 찍히는지 확인 -6. **Swagger** - - springdoc-openapi 설정 후, 공통 DTO가 API 스펙에 잘 노출되는지 확인 - -이 문서를 기반으로, -각 서비스 팀은 **인증, 로깅, 스케줄링, Redis 큐 구조를 공통 규약에 맞춰 재사용**할 수 있습니다. + * URL 레벨: `kri.security.public-paths` (기본 + 추가) + * 메소드 레벨: `@PermitAll`, `@PreAuthorize("hasRole('1')")` 등 사용 \ No newline at end of file diff --git a/build.gradle b/build.gradle index 8e666b1..1cbd6b4 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } //버전 변경은 여기서 -def commonVer = "1.0.4" +def commonVer = "1.0.15" group = 'com.kri.common' version = commonVer @@ -35,9 +35,14 @@ dependencies { // Security Core api 'org.springframework.security:spring-security-core' + // ✅ HttpSecurity, SecurityFilterChain, WebSecurityCustomizer 등 들어있는 모듈들 + compileOnly 'org.springframework.security:spring-security-config' + compileOnly 'org.springframework.security:spring-security-web' // Swagger / OpenAPI 어노테이션 (@Schema 등) - 컴파일용 compileOnly 'io.swagger.core.v3:swagger-annotations:2.2.25' + compileOnly 'io.swagger.core.v3:swagger-models:2.2.25' + compileOnly 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0' // Lombok compileOnly 'org.projectlombok:lombok' diff --git a/src/main/java/com/kri/common/security/ApiKeyAuthFilter.java b/src/main/java/com/kri/common/security/ApiKeyAuthFilter.java new file mode 100644 index 0000000..0ab38e9 --- /dev/null +++ b/src/main/java/com/kri/common/security/ApiKeyAuthFilter.java @@ -0,0 +1,69 @@ +package com.kri.common.security; + +import com.kri.common.auth.apikey.ApiKeyProperties; +import com.kri.common.auth.apikey.ApiKeyUserClaimsProvider; +import com.kri.common.auth.jwt.JwtService; +import com.kri.common.auth.jwt.JwtUserClaimsDto; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.Optional; + +@RequiredArgsConstructor +public class ApiKeyAuthFilter extends OncePerRequestFilter { + + private final ApiKeyProperties properties; + private final ApiKeyUserClaimsProvider userClaimsProvider; + private final JwtService jwtService; // DTO -> Authentication 변환 용도 + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + + // 기능이 꺼져 있으면 바로 패스 + if (!properties.isEnabled()) { + filterChain.doFilter(request, response); + return; + } + + // 이미 다른 필터에서 Authentication 을 세팅했다면 건너뜀 + if (SecurityContextHolder.getContext().getAuthentication() != null) { + filterChain.doFilter(request, response); + return; + } + + String headerName = properties.getHeaderName(); + String apiKey = request.getHeader(headerName); + + if (apiKey == null || apiKey.isBlank()) { + filterChain.doFilter(request, response); + return; + } + + // 서비스 쪽 구현체에서 apiKey -> JwtUserClaimsDto 매핑 + Optional userOpt = userClaimsProvider.findUserByApiKey(apiKey); + + if (userOpt.isPresent()) { + JwtUserClaimsDto dto = userOpt.get(); + + // 공통 JwtService 가 제공하는 DTO -> Authentication 변환 사용 + Authentication auth = jwtService.toAuthentication(dto); + SecurityContextHolder.getContext().setAuthentication(auth); + } else { + // 유효하지 않은 API-Key → 그냥 Authentication 세팅 안 함 + // 이후 anyRequest().authenticated() 에서 401/403 처리 + } + + filterChain.doFilter(request, response); + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/security/JwtAuthenticationFilter.java b/src/main/java/com/kri/common/security/JwtAuthenticationFilter.java new file mode 100644 index 0000000..b62fa04 --- /dev/null +++ b/src/main/java/com/kri/common/security/JwtAuthenticationFilter.java @@ -0,0 +1,48 @@ +package com.kri.common.security; + +import com.kri.common.auth.jwt.JwtService; +import io.jsonwebtoken.JwtException; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@RequiredArgsConstructor +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + private final JwtService jwtService; + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + // 이미 인증이 있다면 건너뜀 (API-Key 필터 등에서 먼저 세팅했을 수 있음) + if (SecurityContextHolder.getContext().getAuthentication() == null) { + String header = request.getHeader("Authorization"); + if (header != null && header.startsWith("Bearer ")) { + String token = header.substring("Bearer ".length()); + try { + // ★ 오직 "정상 JWT" 만 처리 + Authentication auth = jwtService.toAuthentication(token); + SecurityContextHolder.getContext().setAuthentication(auth); + } catch (JwtException ex) { + // 여기서 바로 401 내고 끊고 싶으면 이렇게 할 수도 있고: + // response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + // return; + // + // 기본값은 "인증 세팅 안 함" + 나머지 필터 → 결국 anyRequest().authenticated()에서 401 떨어짐 + } + } + } + + filterChain.doFilter(request, response); + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/security/KriSecurityAutoConfiguration.java b/src/main/java/com/kri/common/security/KriSecurityAutoConfiguration.java new file mode 100644 index 0000000..645b381 --- /dev/null +++ b/src/main/java/com/kri/common/security/KriSecurityAutoConfiguration.java @@ -0,0 +1,87 @@ +package com.kri.common.security; + +import com.kri.common.auth.apikey.ApiKeyAuthFilter; +import com.kri.common.auth.apikey.ApiKeyProperties; +import com.kri.common.auth.apikey.ApiKeyUserClaimsProvider; +import com.kri.common.auth.jwt.JwtProperties; +import com.kri.common.auth.jwt.JwtService; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@AutoConfiguration(before = SecurityAutoConfiguration.class) +@EnableConfigurationProperties({KriSecurityProperties.class, JwtProperties.class}) +@ConditionalOnProperty(prefix = "kri.security", name = "enabled", havingValue = "true", matchIfMissing = true) +@EnableMethodSecurity( + jsr250Enabled = true, + prePostEnabled = true +) +@RequiredArgsConstructor +public class KriSecurityAutoConfiguration { + + private final KriSecurityProperties securityProperties; + private final JwtProperties jwtProperties; + + @Bean + @ConditionalOnMissingBean + public JwtService jwtService(JwtProperties properties) { + return new JwtService(properties); + } + + @Bean + @ConditionalOnMissingBean + public JwtAuthenticationFilter jwtAuthenticationFilter(JwtService jwtService) { + return new JwtAuthenticationFilter(jwtService); + } + + /** + * 서비스에서 SecurityFilterChain 을 따로 정의하지 않으면 + * 이 기본 Security 구성이 적용된다. + */ + @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") + @Bean + @ConditionalOnMissingBean(SecurityFilterChain.class) + public SecurityFilterChain kriSecurityFilterChain( + HttpSecurity http, + ObjectProvider apiKeyAuthFilterProvider, + JwtAuthenticationFilter jwtAuthenticationFilter + ) throws Exception { + + http + .httpBasic(AbstractHttpConfigurer::disable) + .csrf(AbstractHttpConfigurer::disable) + .cors(Customizer.withDefaults()) + .sessionManagement(session -> + session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) + ) + .authorizeHttpRequests(auth -> { + // ✅ yaml에서 정의한 public-paths 전부 permitAll + if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths().isEmpty()) { + auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new)).permitAll(); + } + // ✅ 나머지는 전부 인증 필요 + auth.anyRequest().authenticated(); + }); + + // ✅ API Key 필터가 존재하면 먼저 태움 + apiKeyAuthFilterProvider.ifAvailable(filter -> + http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class) + ); + // ✅ 그 다음 JWT 필터 + http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/security/KriSecurityProperties.java b/src/main/java/com/kri/common/security/KriSecurityProperties.java new file mode 100644 index 0000000..dbcb569 --- /dev/null +++ b/src/main/java/com/kri/common/security/KriSecurityProperties.java @@ -0,0 +1,28 @@ +package com.kri.common.security; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.List; + +@Getter +@Setter +@ConfigurationProperties(prefix = "kri.security") +public class KriSecurityProperties { + + /** + * 이 자동구성 사용 여부 + */ + private boolean enabled = true; + + /** + * 인증 없이 허용할 URL 패턴들 + * 서비스에서 application.yml로 오버라이드 + */ + private List publicPaths = List.of( + "/v3/api-docs/**", + "/swagger-ui.html", + "/swagger-ui/**" + ); +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/swagger/KriSwaggerAutoConfiguration.java b/src/main/java/com/kri/common/swagger/KriSwaggerAutoConfiguration.java new file mode 100644 index 0000000..0e9d789 --- /dev/null +++ b/src/main/java/com/kri/common/swagger/KriSwaggerAutoConfiguration.java @@ -0,0 +1,70 @@ +package com.kri.common.swagger; + +import com.kri.common.auth.apikey.ApiKeyProperties; +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import lombok.RequiredArgsConstructor; +import org.springdoc.core.models.GroupedOpenApi; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; + +@AutoConfiguration +@EnableConfigurationProperties(KriSwaggerProperties.class) +@ConditionalOnClass({OpenAPI.class, GroupedOpenApi.class}) +@ConditionalOnProperty(prefix = "kri.swagger", name = "enabled", havingValue = "true", matchIfMissing = true) +@RequiredArgsConstructor +public class KriSwaggerAutoConfiguration { + + private final KriSwaggerProperties properties; + private final ApiKeyProperties apiKeyProperties; // apikey.header-name 읽어오기 위해 + + @Bean + @ConditionalOnMissingBean + public OpenAPI kriOpenAPI() { + + // 🔐 JWT Bearer + API-Key 스키마 정의 + Components components = new Components() + .addSecuritySchemes("BearerAuth", + new SecurityScheme() + .type(SecurityScheme.Type.HTTP) + .scheme("bearer") + .bearerFormat("JWT")) + .addSecuritySchemes("ApiKeyAuth", + new SecurityScheme() + .type(SecurityScheme.Type.APIKEY) + .in(SecurityScheme.In.HEADER) + .name(apiKeyProperties.getHeaderName())); // 예: X-API-Key + + // 🔐 기본적으로 두 보안 스키마를 전역에 적용 + SecurityRequirement securityRequirement = new SecurityRequirement() + .addList("BearerAuth") + .addList("ApiKeyAuth"); + + return new OpenAPI() + .components(components) + .addSecurityItem(securityRequirement) + .info(new Info() + .title(properties.getTitle()) + .description(properties.getDescription()) + .version(properties.getVersion()) + ); + } + + @Bean + @ConditionalOnMissingBean + public GroupedOpenApi kriGroupedOpenApi() { + GroupedOpenApi.Builder builder = GroupedOpenApi.builder() + .group("kri-api"); + if (properties.getBasePackage() != null) { + builder.packagesToScan(properties.getBasePackage()); + } + return builder.build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/swagger/KriSwaggerProperties.java b/src/main/java/com/kri/common/swagger/KriSwaggerProperties.java new file mode 100644 index 0000000..7816717 --- /dev/null +++ b/src/main/java/com/kri/common/swagger/KriSwaggerProperties.java @@ -0,0 +1,22 @@ +package com.kri.common.swagger; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@Getter +@Setter +@ConfigurationProperties(prefix = "kri.swagger") +public class KriSwaggerProperties { + + private boolean enabled = true; + + private String title = "KRI API"; + private String description = "KRI Common API Docs"; + private String version = "v1"; + + /** + * 문서화할 base package (null 이면 전체) + */ + private String basePackage; +} diff --git a/src/main/java/com/kri/common/webmvc/IpAccessControlInterceptor.java b/src/main/java/com/kri/common/webmvc/IpAccessControlInterceptor.java new file mode 100644 index 0000000..44457bd --- /dev/null +++ b/src/main/java/com/kri/common/webmvc/IpAccessControlInterceptor.java @@ -0,0 +1,26 @@ +package com.kri.common.webmvc; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.web.servlet.HandlerInterceptor; + +@RequiredArgsConstructor +public class IpAccessControlInterceptor implements HandlerInterceptor { + + private final IpAccessControlService ipAccessControlService; + + @Override + public boolean preHandle(HttpServletRequest request, + HttpServletResponse response, + Object handler) throws Exception { + + String clientIpAddress = IpUtil.getClientIp(request); + if (!ipAccessControlService.isAccessible(clientIpAddress)) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return false; + } + + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/webmvc/IpAccessControlService.java b/src/main/java/com/kri/common/webmvc/IpAccessControlService.java new file mode 100644 index 0000000..65b0345 --- /dev/null +++ b/src/main/java/com/kri/common/webmvc/IpAccessControlService.java @@ -0,0 +1,20 @@ +package com.kri.common.webmvc; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.web.util.matcher.IpAddressMatcher; + +import java.util.List; + +@RequiredArgsConstructor +public class IpAccessControlService { + + private final KriIpAccessProperties properties; + + public boolean isAccessible(String ipAddress) { + List cidrs = properties.getEffectiveCidrs(); + + return cidrs.stream() + .map(IpAddressMatcher::new) + .anyMatch(matcher -> matcher.matches(ipAddress)); + } +} diff --git a/src/main/java/com/kri/common/webmvc/IpUtil.java b/src/main/java/com/kri/common/webmvc/IpUtil.java new file mode 100644 index 0000000..904c83e --- /dev/null +++ b/src/main/java/com/kri/common/webmvc/IpUtil.java @@ -0,0 +1,27 @@ +package com.kri.common.webmvc; + +import jakarta.servlet.http.HttpServletRequest; + +public final class IpUtil { + + private IpUtil() { + } + + public static String getClientIp(HttpServletRequest request) { + // 1. Proxy 환경 고려: X-Forwarded-For 헤더 우선 + String xff = request.getHeader("X-Forwarded-For"); + if (xff != null && !xff.isBlank()) { + // X-Forwarded-For: client, proxy1, proxy2 ... + return xff.split(",")[0].trim(); + } + + // 2. 그 다음 X-Real-IP + String realIp = request.getHeader("X-Real-IP"); + if (realIp != null && !realIp.isBlank()) { + return realIp; + } + + // 3. 최후 fallback + return request.getRemoteAddr(); + } +} diff --git a/src/main/java/com/kri/common/webmvc/KriIpAccessProperties.java b/src/main/java/com/kri/common/webmvc/KriIpAccessProperties.java new file mode 100644 index 0000000..c41c085 --- /dev/null +++ b/src/main/java/com/kri/common/webmvc/KriIpAccessProperties.java @@ -0,0 +1,44 @@ +package com.kri.common.webmvc; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Getter +@Setter +@ConfigurationProperties(prefix = "kri.webmvc.ip") +public class KriIpAccessProperties { + + /** + * 공통에서 고정으로 들고 갈 기본 CIDR 들 + * → setter 없음 (외부에서 못 바꿈) + */ + private final List defaultCidrs = List.of( + "127.0.0.1/32", // 로컬 IPv4 + "::1/128", // 로컬 IPv6 + "10.10.13.0/24", //석오 내부망 + "211.254.145.128/25" //석오 내부망 외부 IP + ); + + /** + * 서비스에서 추가로 넣고 싶은 CIDR 목록 + * application.yml / properties 로 바인딩되는 리스트 + * + * 예) kri.webmvc.ip.additional-cidrs[0]=10.10.0.0/16 + */ + private List additionalCidrs = new ArrayList<>(); + + /** + * 기본 + 추가를 합친 최종 목록 + */ + public List getEffectiveCidrs() { + return Stream.concat(defaultCidrs.stream(), additionalCidrs.stream()) + .distinct() + .collect(Collectors.toList()); + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/webmvc/KriWebMvcAutoConfiguration.java b/src/main/java/com/kri/common/webmvc/KriWebMvcAutoConfiguration.java new file mode 100644 index 0000000..9501f7e --- /dev/null +++ b/src/main/java/com/kri/common/webmvc/KriWebMvcAutoConfiguration.java @@ -0,0 +1,63 @@ +package com.kri.common.webmvc; + +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@AutoConfiguration +@EnableConfigurationProperties(KriIpAccessProperties.class) +@ConditionalOnProperty(name = "common.webmvc.enabled", matchIfMissing = true) +@RequiredArgsConstructor +public class KriWebMvcAutoConfiguration { + + private final KriIpAccessProperties ipProps; // 생성자 주입 (RequiredArgsConstructor) + + @Bean + @ConditionalOnMissingBean + public IpAccessControlService ipAccessControlService(KriIpAccessProperties ipProps) { + return new IpAccessControlService(ipProps); + } + + @Bean + @ConditionalOnMissingBean + public IpAccessControlInterceptor ipAccessControlInterceptor(IpAccessControlService service) { + return new IpAccessControlInterceptor(service); + } + + // 선택 주입: 있으면 쓰고, 없으면 안 씀 + private final ObjectProvider ipAccessControlInterceptorProvider; + + /** + * 실제로 WebMvc 설정을 하는 WebMvcConfigurer Bean + */ + @Bean + public WebMvcConfigurer kriCommonWebMvcConfigurer() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + // 기본 CORS – 필요하면 나중에 조정 + registry.addMapping("/**") + .allowedOriginPatterns("*") + .allowedMethods("*") + .allowedHeaders("*") + .allowCredentials(true); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + ipAccessControlInterceptorProvider.ifAvailable(interceptor -> + registry.addInterceptor(interceptor) + .order(1) + .addPathPatterns("/swagger-ui/**", "/v3/api-docs/**") + ); + } + }; + } +} \ No newline at end of file diff --git a/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 54675c2..73042cc 100644 --- a/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1,4 +1,7 @@ +com.kri.common.auth.jwt.JwtAutoConfiguration +com.kri.common.security.KriSecurityAutoConfiguration com.kri.common.web.CommonWebAutoConfiguration +com.kri.common.webmvc.KriWebMvcAutoConfiguration +com.kri.common.swagger.KriSwaggerAutoConfiguration com.kri.common.redis.CommonRedisAutoConfiguration com.kri.common.scheduling.CommonSchedulingAutoConfiguration -com.kri.common.auth.jwt.JwtAutoConfiguration