From 2a35b62a48a9eb935d57eaf44e4fe42b837af12b Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Wed, 19 Nov 2025 08:43:05 +0900 Subject: [PATCH] =?UTF-8?q?251119=5F01=5FENH=20:=20Junie=EB=A1=9C=20?= =?UTF-8?q?=EC=86=8C=EC=8A=A4=EC=BD=94=EB=93=9C=20=EB=B0=8F=20README=20?= =?UTF-8?q?=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 598 ++++++++++++++++-- build.gradle | 2 +- .../com/kri/common/auth/jwt/JwtService.java | 24 +- .../kri/common/security/ApiKeyAuthFilter.java | 69 -- 4 files changed, 568 insertions(+), 125 deletions(-) delete mode 100644 src/main/java/com/kri/common/security/ApiKeyAuthFilter.java diff --git a/README.md b/README.md index 30c7e73..c31ab3d 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,249 @@ Spring Boot 기반 사내 서비스에서 공통으로 사용하는 기능들을 --- +## 빠른 시작(10분 내 적용) + +아래 순서대로 복붙하면, JWT 발급/검증과 Swagger까지 바로 동작 확인이 가능합니다. + +1) Gradle 설정 추가 + +`example-service/build.gradle` + +```gradle +repositories { + mavenCentral() + + // 사내 Gitea Maven 레지스트리 + def giteaUser = findProperty("giteaUser") ?: "" + def giteaToken = findProperty("giteaToken") ?: "" + maven { + name = "gitea" + url = uri("https://gitea.kric.com/api/packages/KRi/maven") + credentials { + username = giteaUser + password = giteaToken + } + } +} + +dependencies { + 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 UI + implementation "org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0" + + // KriCommon + implementation "com.kri.common:starter:1.0.15" +} +``` + +2) application.yml 설정(최소값) + +`example-service/src/main/resources/application.yml` + +```yaml +spring: + application: + name: example-service + +server: + port: 8080 + +logging: + file: + path: logs + level: + root: INFO + com.kri: DEBUG + +kri: + auth: + jwt: + # HS256 기준 UTF-8 32바이트 이상 필수 (라이브러리에서 검증) + secret: "서비스별로_반드시_교체하세요_최소_32자리_랜덤키_예시_1234567890" + issuer: "kri-it" + security: + public-paths: + - "/v3/api-docs/**" + - "/swagger-ui.html" + - "/swagger-ui/**" + - "/actuator/health" +``` + +3) 로그인(토큰 발급) 샘플 엔드포인트 추가 + +서비스에 아래 두 클래스를 추가해 JWT 발급을 확인합니다. + +``` +// package 예시는 서비스 상황에 맞게 변경하세요. +@org.springframework.stereotype.Service +@lombok.RequiredArgsConstructor +public class AuthService { + private final com.kri.common.auth.jwt.JwtService jwtService; + + public String login(String username) { + var claims = com.kri.common.auth.jwt.JwtUserClaimsDto.builder() + .userId(username) + .userTeam("IT") + .userName("홍길동") + .role(1) + .build(); + return jwtService.generateAccessToken(claims); + } +} + +@org.springframework.web.bind.annotation.RestController +@org.springframework.web.bind.annotation.RequestMapping("/auth") +@lombok.RequiredArgsConstructor +class AuthController { + private final AuthService authService; + + @org.springframework.web.bind.annotation.PostMapping("/login") + public java.util.Map login(@org.springframework.web.bind.annotation.RequestParam String username) { + String token = authService.login(username); + return java.util.Map.of("accessToken", token); + } +} +``` + +4) 동작 확인(curl) + +```bash +# 1) 토큰 발급 +curl -X POST "http://localhost:8080/auth/login?username=user1" +# => { "accessToken": "eyJhbGciOiJI..." } + +# 2) Swagger 접근(기본 public-paths 허용) +open http://localhost:8080/swagger-ui/index.html + +# 3) 보호된 API 호출 예시 (서비스 API가 있다고 가정) +TOKEN={발급받은_토큰} +curl -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/secure +``` + +5) 선택: 외부 API Key 사용 시 구현 1개만 추가 + +``` +@org.springframework.stereotype.Component +public class ExampleApiKeyUserClaimsProvider implements com.kri.common.auth.apikey.ApiKeyUserClaimsProvider { + @Override + public java.util.Optional findUserByApiKey(String apiKey) { + if ("DEMO-KEY-1234".equals(apiKey)) { + return java.util.Optional.of( + com.kri.common.auth.jwt.JwtUserClaimsDto.builder() + .userId("external") + .userTeam("EXT") + .userName("외부") + .role(9) + .build() + ); + } + return java.util.Optional.empty(); + } +} +``` + +application.yml에 아래를 추가하세요. + +```yaml +kri: + auth: + apikey: + enabled: true + header-name: "X-API-Key" +``` + +이제 `X-API-Key: DEMO-KEY-1234` 헤더만으로도 인증이 선행되고, JWT 없을 때 대체 인증으로 작동합니다. + +--- + +## 0. 아키텍처 개요 + +이 저장소는 다수의 서비스에서 공통으로 재사용할 수 있는 경량 Starter 형태의 라이브러리를 목표로 합니다. 핵심 원칙은 다음과 같습니다. + +- 최소 의존성: starter가 과도한 런타임 의존성을 강제하지 않도록 compileOnly 위주 구성 (서비스가 필요한 starter를 직접 선언) +- 자가완결형 AutoConfiguration: 기본값으로 바로 동작하지만, Bean 오버라이드와 프로퍼티로 손쉽게 커스터마이즈 가능 +- 분리/응집: 인증/시큐리티/웹/문서화/인프라(redis, scheduling) 등을 느슨히 결합하여 모듈 경계를 유지 + +### 0.1 패키지 레이어와 의존 방향 + +- com.kri.common.auth.jwt: JWT 프로퍼티/DTO/유틸(JwtService) +- com.kri.common.auth.apikey: API Key 프로퍼티/필터/확장 포인트(ApiKeyUserClaimsProvider) +- com.kri.common.security: 공통 보안 자동구성(SecurityFilterChain, 필터 배치 등) +- com.kri.common.web: 공통 예외 처리, Trace 필터, MDC 지원 +- com.kri.common.webmvc: CORS 기본값, Swagger 접근 IP 제어 인터셉터 +- com.kri.common.swagger: OpenAPI/Swagger 기본 설정 및 SecurityScheme 구성 +- com.kri.common.redis: Redis 편의 헬퍼 및 자동 구성 (선택 사용) +- com.kri.common.scheduling: 스케줄링 자동 활성화 (선택 사용) + +권장 의존 방향(순환 금지): +- auth.jwt, auth.apikey → 다른 모듈에 의존하지 않음(핵심 도메인 유틸) +- security → auth.* 에 의존(필터 순서/체인 구성) +- web, webmvc → spring-web 중심, security에 의존하지 않음 +- swagger → 선택, 나머지에 의존하지 않도록 구성 +- redis, scheduling → 선택, spring-data-redis / scheduling만 전제 + +### 0.2 AutoConfiguration 로딩과 오버라이드 전략 + +자동 구성은 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports로 등록되며, 다음 순서/특징을 가집니다. + +1) com.kri.common.auth.jwt.JwtAutoConfiguration +- JwtProperties 바인딩, JwtService, ApiKeyAuthFilter 등 기초 컴포넌트 제공 + +2) com.kri.common.security.KriSecurityAutoConfiguration +- SecurityFilterChain 기본 구성, @EnableMethodSecurity 활성화, 필터 체인에 ApiKey → JWT 순서로 필터 삽입 +- before = SecurityAutoConfiguration 으로 Spring 기본 보안 자동구성보다 먼저 개입 + +3) com.kri.common.web.CommonWebAutoConfiguration, com.kri.common.webmvc.KriWebMvcAutoConfiguration +- 공통 예외/로깅, CORS, Swagger 접근 IP 제어 인터셉터 + +4) com.kri.common.swagger.KriSwaggerAutoConfiguration +- OpenAPI/Swagger 설정, Bearer/JWT + API Key SecurityScheme 등록 + +5) com.kri.common.redis.CommonRedisAutoConfiguration, com.kri.common.scheduling.CommonSchedulingAutoConfiguration +- 선택 기능: RedisQueueHelper, @EnableScheduling + +오버라이드 규칙: +- 동일 타입의 Bean을 서비스에서 정의하면 @ConditionalOnMissingBean에 의해 서비스 정의가 우선 +- 프로퍼티로 on/off 토글(@ConditionalOnProperty) + +### 0.3 Security 필터 체인 흐름(기본값) + +- Stateless 세션, CSRF 비활성화, CORS 기본 허용 +- public-paths는 permitAll, 그 외 anyRequest().authenticated() +- 필터 순서: ApiKeyAuthFilter → JwtAuthenticationFilter → UsernamePasswordAuthenticationFilter + - 외부/파트너용 API Key가 있다면 먼저 인증 세팅, 없으면 Bearer JWT 처리 + +### 0.4 설정 네임스페이스 정리 + +- kri.auth.jwt.*: 시크릿/발급자/만료시간 등 +- kri.auth.apikey.*: 사용 여부/헤더 이름 +- kri.security.*: Security 자동 구성 on/off, public-paths +- kri.swagger.*: 문서화 on/off, 제목/설명/버전/스캔 패키지 +- kri.webmvc.*: CORS, Swagger 접근 IP 제어 +- common.web.enabled: 공통 예외/Trace 필터 on/off +- common.redis.enabled: RedisQueueHelper 사용 여부 +- common.scheduling.enabled: 스케줄링 사용 여부 + +### 0.5 확장 포인트(서비스 구현/대체 지점) + +- ApiKeyUserClaimsProvider: API Key → 사용자 클레임 매핑 구현체 제공 +- SecurityFilterChain: 필요 시 서비스에서 직접 정의하여 전면 대체 가능 +- WebMvcConfigurer: 서비스에서 별도 CORS/인터셉터 전략 추가 가능 +- Swagger GroupedOpenApi: 서비스에서 그룹/패키지 전략 세분화 가능 + +### 0.6 운영 관점 가이드(권장) + +- JWT 시크릿: HS256 기준 UTF-8 32바이트 이상 강제(JwtService.init 검증) — 서비스별 난수 기반 키 사용 +- public-paths 거버넌스: 최소 공개 원칙, 변경 시 보안 리뷰 절차 권장 +- Swagger 접근 제어: 기본 CIDR + 서비스별 추가 CIDR만 설정하도록 유지(운영망 노출 주의) +- 의존성 정책: starter에는 compileOnly를 유지하여 소비자 서비스가 필요한 starter를 명시하도록 함 +- 버전 정책: build.gradle의 commonVer로 일원화, 기능 추가는 마이너/패치 버전 준수(semver) + +이 섹션은 상위 수준에서 구조를 빠르게 이해하고, 서비스 적용 시 확장/대체 지점을 명확히 하기 위해 추가되었습니다. + ## 1. 의존성 추가 ### 1.1. Gradle 예시 (권장) @@ -174,7 +417,7 @@ common: #### 4.1.1. JwtProperties -```java +``` @ConfigurationProperties(prefix = "kri.auth.jwt") public class JwtProperties { private String secret; // HMAC 시크릿 키 (기본값 존재, 서비스에서 override 권장) @@ -195,7 +438,7 @@ public class JwtProperties { #### 4.1.2. JwtUserClaimsDto -```java +``` package com.kri.common.auth.jwt; import io.swagger.v3.oas.annotations.media.Schema; @@ -227,7 +470,7 @@ public class JwtUserClaimsDto { 주요 메서드: -```java +``` public class JwtService { // Access Token 생성 (DTO → JWT 문자열) @@ -248,7 +491,7 @@ public class JwtService { **로그인 예시** -```java +``` @Service @RequiredArgsConstructor public class AuthService { @@ -277,7 +520,7 @@ public class AuthService { #### 4.2.1. ApiKeyProperties -```java +``` @ConfigurationProperties(prefix = "kri.auth.apikey") public class ApiKeyProperties { private boolean enabled = false; @@ -294,7 +537,7 @@ public class ApiKeyProperties { #### 4.2.2. ApiKeyUserClaimsProvider (서비스 구현 필요) -```java +``` public interface ApiKeyUserClaimsProvider { /** @@ -309,7 +552,7 @@ public interface ApiKeyUserClaimsProvider { **서비스 구현 예시 (`example-service`)** -```java +``` @Component @RequiredArgsConstructor public class ExampleApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider { @@ -347,7 +590,7 @@ public class ExampleApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider #### 4.3.1. KriSecurityProperties -```java +``` @ConfigurationProperties(prefix = "kri.security") public class KriSecurityProperties { @@ -400,20 +643,24 @@ kri: **메소드 레벨 권한 예시** -```java -@RestController -@RequestMapping("/api/example") +``` +@org.springframework.web.bind.annotation.RestController +@org.springframework.web.bind.annotation.RequestMapping("/api/example") public class ExampleController { // 누구나 접근 가능하게 열고 싶다면: @jakarta.annotation.security.PermitAll - @GetMapping("/public") - public String publicApi() { ... } + @org.springframework.web.bind.annotation.GetMapping("/public") + public String publicApi() { + return "ok"; + } // 특정 권한 레벨 사용 (예: ROLE_1) @org.springframework.security.access.prepost.PreAuthorize("hasRole('1')") - @GetMapping("/admin-only") - public String adminOnly() { ... } + @org.springframework.web.bind.annotation.GetMapping("/admin-only") + public String adminOnly() { + return "admin"; + } } ``` @@ -426,7 +673,7 @@ public class ExampleController { #### 4.4.1. KriSwaggerProperties -```java +``` @ConfigurationProperties(prefix = "kri.swagger") public class KriSwaggerProperties { private boolean enabled = true; @@ -479,7 +726,7 @@ kri: #### 4.5.1. KriWebMvcAutoConfiguration -```java +``` @AutoConfiguration @EnableConfigurationProperties(KriIpAccessProperties.class) @ConditionalOnProperty(prefix = "kri.webmvc", name = "enabled", havingValue = "true", matchIfMissing = true) @@ -525,7 +772,7 @@ public class KriWebMvcAutoConfiguration { #### 4.5.2. KriIpAccessProperties & IP 설정 -```java +``` @ConfigurationProperties(prefix = "kri.webmvc.ip") public class KriIpAccessProperties { @@ -571,16 +818,22 @@ kri: #### 4.5.3. CommonWebAutoConfiguration -```java -@AutoConfiguration -@ConditionalOnProperty(name = "common.web.enabled", matchIfMissing = true) +``` +@org.springframework.boot.autoconfigure.AutoConfiguration +@org.springframework.boot.autoconfigure.condition.ConditionalOnProperty(name = "common.web.enabled", matchIfMissing = true) public class CommonWebAutoConfiguration { - @Bean - public ErrorAdvice errorAdvice() { ... } + @org.springframework.context.annotation.Bean + public com.kri.common.web.ErrorAdvice errorAdvice() { + // 예시 코드: 실제 라이브러리에서는 구현되어 있으므로, 서비스에서는 별도 정의 불필요 + return null; + } - @Bean - public FilterRegistrationBean traceFilter() { ... } + @org.springframework.context.annotation.Bean + public org.springframework.boot.web.servlet.FilterRegistrationBean traceFilter() { + // 예시 코드: 실제 라이브러리에서는 구현되어 있으므로, 서비스에서는 별도 정의 불필요 + return null; + } } ``` @@ -594,18 +847,28 @@ public class CommonWebAutoConfiguration { #### 4.6.1. CommonRedisAutoConfiguration -```java -@AutoConfiguration -@ConditionalOnClass(RedisTemplate.class) -@ConditionalOnProperty(prefix = "common.redis", name = "enabled", havingValue = "true") -@ConditionalOnBean(RedisConnectionFactory.class) +``` +@org.springframework.boot.autoconfigure.AutoConfiguration +@org.springframework.boot.autoconfigure.condition.ConditionalOnClass(org.springframework.data.redis.core.RedisTemplate.class) +@org.springframework.boot.autoconfigure.condition.ConditionalOnProperty(prefix = "common.redis", name = "enabled", havingValue = "true") +@org.springframework.boot.autoconfigure.condition.ConditionalOnBean(org.springframework.data.redis.connection.RedisConnectionFactory.class) public class CommonRedisAutoConfiguration { - @Bean @ConditionalOnMissingBean - public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory cf) { ... } + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean + public org.springframework.data.redis.core.StringRedisTemplate stringRedisTemplate( + org.springframework.data.redis.connection.RedisConnectionFactory cf) { + // 예시 코드: 실제 라이브러리에서는 자동 구성됨 + return new org.springframework.data.redis.core.StringRedisTemplate(cf); + } - @Bean @ConditionalOnMissingBean - public RedisQueueHelper redisQueueHelper(StringRedisTemplate rt) { ... } + @org.springframework.context.annotation.Bean + @org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean + public com.kri.common.redis.RedisQueueHelper redisQueueHelper( + org.springframework.data.redis.core.StringRedisTemplate rt) { + // 예시 코드: 실제 라이브러리에서는 자동 구성됨 + return new com.kri.common.redis.RedisQueueHelper(rt); + } } ``` @@ -617,7 +880,7 @@ public class CommonRedisAutoConfiguration { #### 4.6.2. RedisQueueHelper 사용 예시 -```java +``` @Service @RequiredArgsConstructor public class ExportQueueService { @@ -638,7 +901,7 @@ public class ExportQueueService { ### 4.7. 스케줄링 (`com.kri.common.scheduling`) -```java +``` @AutoConfiguration @EnableScheduling @ConditionalOnProperty(prefix = "common.scheduling", name = "enabled", havingValue = "true") @@ -675,6 +938,214 @@ common: --- +### 4.9. BusinessException 사용 사용 가이드 + +`BusinessException`은 **도메인/업무 에러를 공통 형식으로 표현하기 위한 예외 클래스**입니다. +서비스 코드에서 이 예외만 잘 던져주면, 공통 `ErrorAdvice`가 자동으로 잡아서 **일관된 JSON 응답 + 로그**를 만들어 줍니다. + +#### 4.9.1. 핵심 개념 + +`com.kri.common.web.BusinessException` 주요 필드(개념): + +- `HttpStatus status` : HTTP 상태 코드 (예: 400, 403, 404, 409, 422, 500 등) +- `String code` : 비즈니스 에러 코드 (예: `"USER_NOT_FOUND"`, `"DUPLICATE_ID"`) +- `Map extras` : 추가 정보 (userId, 필드명, 파라미터 등) + +**던지기만 하면** `ErrorAdvice`가 잡아서 `ProblemDetail` 포맷으로 응답을 내려줍니다. + + +#### 4.9.2. 기본 사용 패턴 + +* 4.9.2.1. Not Found (404) + +``` +import com.kri.common.web.BusinessException; + +public User getUserOrThrow(String userId) { + return userRepository.findById(userId) + .orElseThrow(() -> + BusinessException.notFound( + "USER_NOT_FOUND", + "해당 사용자를 찾을 수 없습니다." + ).with("userId", userId) // extras에 userId 추가 + ); +} +``` +- HTTP 상태: 404 +- code: "USER_NOT_FOUND" +- message: "해당 사용자를 찾을 수 없습니다." +- extras: { "userId": "..." } + +* 4.9.2.2. Conflict (409) +``` +if (userRepository.existsByLoginId(loginId)) { + throw BusinessException.conflict( + "DUPLICATE_LOGIN_ID", + "이미 사용 중인 로그인 ID입니다." + ).with("loginId", loginId); +} +``` + +* 4.9.2.3. Forbidden (403) +``` +if (!currentUser.canAccess(targetProject)) { + throw BusinessException.forbidden( + "NO_PERMISSION", + "해당 프로젝트에 접근 권한이 없습니다." + ).with("projectId", projectId); +} +``` + +#### 4.9.3. 임의 상태 코드 지정: of(...) +of(HttpStatus status, String code, String message) 팩토리로 원하는 상태 코드를 직접 지정할 수 있습니다. +``` +throw BusinessException.of( + HttpStatus.BAD_REQUEST, + "INVALID_PARAMETER", + "요청 파라미터가 잘못되었습니다." +).with("param", "startDate"); + +``` +추가 정보를 한 번에 넘기고 싶으면: +``` +Map extras = Map.of( + "param", "startDate", + "reason", "must be before endDate" +); + +throw BusinessException.of( + HttpStatus.UNPROCESSABLE_ENTITY, // 422 + "INVALID_DATE_RANGE", + "날짜 범위가 올바르지 않습니다.", + extras +); +``` +> 실제 구현에는 of(status, code, message, Map) 시그니처가 존재합니다. + +#### 4.9.4. extras 체이닝: with(...) 활용 +with(key, value)는 새로운 예외 인스턴스를 리턴하는 체이닝 메서드입니다. +``` +throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.") + .with("userId", userId) + .with("searchType", "INTRANET"); +``` +* 내부적으로 extras를 복사해 새 인스턴스를 만드는 방식이라, immutable 스타일로 안전하게 체이닝할 수 있습니다. + +#### 4.9.5. Service / Controller에서의 사용 위치 +Service에서 던지고, Controller는 깔끔하게 유지 + + Service 예시 +``` +@Service +@RequiredArgsConstructor +public class UserService { + + private final UserRepository userRepository; + + public UserDto getUser(String userId) { + var user = userRepository.findById(userId) + .orElseThrow(() -> BusinessException.notFound( + "USER_NOT_FOUND", + "사용자를 찾을 수 없습니다." + ).with("userId", userId)); + + return UserDto.from(user); + } +} +``` + +Controller 예시 +``` +@RestController +@RequestMapping("/api/users") +@RequiredArgsConstructor +public class UserController { + + private final UserService userService; + + @GetMapping("/{userId}") + public UserDto getUser(@PathVariable String userId) { + // 여기서는 try/catch 필요 없음 + return userService.getUser(userId); + } +} +``` + +* 비즈니스 예외는 Service 계층에서 던지는 것을 추천 +* Controller는 예외를 그대로 위로 올려보내고, +* ErrorAdvice가 @ExceptionHandler(BusinessException.class)로 처리 + +#### 4.9.6. 실제 응답 JSON 예시 +``` +throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.") + .with("userId", "u-123"); + +``` +요청 URL이 /api/users/u-123인 경우, 응답은 대략 다음과 같은 형태입니다. +```json +{ + "type": "about:blank", + "title": "Not Found", + "status": 404, + "detail": "사용자를 찾을 수 없습니다.", + "code": "USER_NOT_FOUND", + "timestamp": "2025-11-17T12:34:56.789Z", + "path": "/api/users/u-123", + "traceId": "abc123...", + "handler": "UserController#getUser", + "service": "UserService#getUser", + "userId": "u-123" +} +``` +> 이 포맷은 ErrorAdvice에서 공통으로 생성합니다. + +#### 4.9.7. 로그 출력 정책 + +ErrorAdvice 내부 로깅 정책(요약): + +5xx (서버 에러) + +→ ERROR 레벨 + 스택 트레이스 포함 + +400, 403, 404, 409, 422 등 도메인 에러 + +→ WARN 레벨, 스택 트레이스 없이 요약 로그 + +기타 상태코드 + +→ 기본적으로 WARN + +#### 4.9.8. 에러 코드 enum으로 관리하기 (선택) + +서비스에서 에러 코드를 enum으로 관리하면 나중에 유지보수가 쉬워집니다. +``` +public enum UserErrorCodes { + USER_NOT_FOUND, + DUPLICATE_LOGIN_ID, + PASSWORD_MISMATCH +} + +throw BusinessException.notFound( + UserErrorCodes.USER_NOT_FOUND.name(), + "사용자를 찾을 수 없습니다." + ).with("userId", userId); +``` +#### 4.9.9. 요약 + +1. 던지는 쪽 (Service) + * BusinessException.notFound("CODE", "메시지") + * BusinessException.conflict("CODE", "메시지") + * BusinessException.forbidden("CODE", "메시지") + * 필요시 of(status, code, message) + * with("key", value)로 추가 정보(extras) 세팅 +2. 받는 쪽 (Controller) + * 별도 try/catch 필요 없음 + * ErrorAdvice가 자동으로 JSON + 로그 처리 +3. 클라이언트/FE 입장 + * 응답은 ProblemDetail 포맷 + code + extras 일관 구조 + * FE에서는 code 기준으로 에러 분기 처리하면 됨 + +--- ## 5. example-service 적용 요약 1. **의존성 추가** @@ -704,4 +1175,57 @@ common: 5. **권한 제어** * URL 레벨: `kri.security.public-paths` (기본 + 추가) - * 메소드 레벨: `@PermitAll`, `@PreAuthorize("hasRole('1')")` 등 사용 \ No newline at end of file + * 메소드 레벨: `@PermitAll`, `@PreAuthorize("hasRole('1')")` 등 사용 + +--- + +## 6. 서비스 적용 체크리스트(운영 전 최종 점검) + +- JWT 시크릿이 운영용 난수 32바이트 이상인지, 저장소/CI 로그에 노출되지 않는지 확인 +- `kri.security.public-paths` 최소 공개 원칙 적용 여부 점검(로그인/헬스/문서만 허용 권장) +- Swagger 접근 제어 CIDR 확인(운영망 외부 노출 금지) +- 도메인 예외는 BusinessException으로 일원화되어 있는지, FE와 코드/메시지 합의 완료 +- 필요 시 `ApiKeyUserClaimsProvider` 구현 제공 여부 +- 로그 적재 디렉터리와 로테이션 정책 확인(logback-spring.xml 커스터마이즈 필요 여부) +- 스케줄링/Redis 기능 사용 시 프로퍼티 on 여부 및 인프라 준비 + +--- + +## 7. 문제 해결 가이드(Troubleshooting) + +- 애플리케이션 시작 시 "kri.auth.jwt.secret must be at least 32 bytes" 오류 + - 원인: JWT 시크릿 최소 길이 미달 + - 조치: application.yml의 `kri.auth.jwt.secret`를 UTF-8 32바이트 이상 난수로 교체 + +- 모든 요청이 401 Unauthorized + - 원인1: Authorization 헤더에 Bearer 토큰 미포함 + - 원인2: 토큰 만료/서명 불일치(issuer 불일치 포함) + - 조치: 로그인 API로 토큰 재발급, issuer와 secret 확인, 클럭 드리프트 점검 + +- Swagger 페이지가 접근 불가(403/404) + - 원인: IP 접근 제어 또는 public-paths 미설정 + - 조치: `kri.webmvc.ip.additional-cidrs`에 현재 IP 대역 추가 또는 `kri.security.public-paths`에 Swagger 경로 포함 + +- ApiKeyUserClaimsProvider가 동작하지 않음 + - 원인: Bean 미등록 또는 `kri.auth.apikey.enabled=false` + - 조치: 구현체 @Component 등록, 프로퍼티 enabled=true 설정, 헤더 이름 일치 여부 점검 + +--- + +## 8. FAQ + +- Q. API Key와 JWT는 어떻게 같이 쓰나요? + - A. 필터 체인에서 API Key가 먼저 검사되어 인증을 세팅하고, 없거나 실패하면 JWT가 검사됩니다. 외부 파트너는 API Key, 내부/사용자 트래픽은 JWT를 권장합니다. + +- Q. ROLE 매핑은 어디서 바꾸나요? + - A. JwtService.toAuthentication(JwtUserClaimsDto) 내부에서 "ROLE_{숫자}"로 생성합니다. 서비스 정책에 맞게 해당 메서드를 오버라이드하거나 래핑하십시오. + +- Q. 기본 Security를 전면 교체할 수 있나요? + - A. 서비스에서 SecurityFilterChain Bean을 직접 정의하면, `@ConditionalOnMissingBean` 규칙에 의해 서비스 정의가 우선 적용됩니다. + +--- + +## 9. 요구 사양 + +- Java 17+ +- Spring Boot 3.5.x (라이브러리는 Spring Boot BOM 3.5.7 기준) \ No newline at end of file diff --git a/build.gradle b/build.gradle index 1cbd6b4..c85f931 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } //버전 변경은 여기서 -def commonVer = "1.0.15" +def commonVer = "1.0.16" group = 'com.kri.common' version = commonVer diff --git a/src/main/java/com/kri/common/auth/jwt/JwtService.java b/src/main/java/com/kri/common/auth/jwt/JwtService.java index d18571b..de1de89 100644 --- a/src/main/java/com/kri/common/auth/jwt/JwtService.java +++ b/src/main/java/com/kri/common/auth/jwt/JwtService.java @@ -27,10 +27,13 @@ public class JwtService { @PostConstruct public void init() { + // 시크릿 검증: HS256 권장 최소 길이(32바이트 이상) + String secret = properties.getSecret(); + if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length < 32) { + throw new IllegalStateException("kri.auth.jwt.secret must be at least 32 bytes (UTF-8) for HS256"); + } // secret 문자열을 HMAC 키로 전환 - this.key = Keys.hmacShaKeyFor( - properties.getSecret().getBytes(StandardCharsets.UTF_8) - ); + this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8)); } // ====================================================== @@ -65,21 +68,6 @@ public class JwtService { // 토큰 생성 (DTO 기반) // ====================================================== - /** - * JwtUserClaimsDto 기반 Access Token 생성 - * - subject = userId - * - claims: - * userId, userTeam, userName, role - */ - public String generateSystemToken(JwtUserClaimsDto userClaims) { - Map claims = buildClaims(userClaims); - return buildToken( - claims, - userClaims.getUserId(), - properties.getAccessTokenValiditySeconds() - ); - } - /** * JwtUserClaimsDto 기반 Access Token 생성 * - subject = userId diff --git a/src/main/java/com/kri/common/security/ApiKeyAuthFilter.java b/src/main/java/com/kri/common/security/ApiKeyAuthFilter.java deleted file mode 100644 index 0ab38e9..0000000 --- a/src/main/java/com/kri/common/security/ApiKeyAuthFilter.java +++ /dev/null @@ -1,69 +0,0 @@ -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