1300 lines
44 KiB
Markdown
1300 lines
44 KiB
Markdown
# KriCommon Starter
|
|
|
|
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`)
|
|
- 공통 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-spring.xml`)
|
|
|
|
### 공용 HTTP 클라이언트: ExternalApiClient
|
|
|
|
외부 API와 통신하기 위한 경량 공용 모듈을 제공합니다. 추가 의존성 없이 Java 17의 `java.net.http.HttpClient`를 사용합니다.
|
|
|
|
- 패키지: `com.kri.common.http`
|
|
- 주요 클래스: `ExternalApiClient`, `ExternalApiResponse`
|
|
|
|
지원 메서드(문자열 body 기반)
|
|
- `ExternalApiResponse get(String url, Map<String,String> headers)`
|
|
- `ExternalApiResponse post(String url, Map<String,String> headers, String body)`
|
|
- `ExternalApiResponse put(String url, Map<String,String> headers, String body)`
|
|
- `ExternalApiResponse patch(String url, Map<String,String> headers, String body)`
|
|
- `ExternalApiResponse delete(String url, Map<String,String> headers)`
|
|
|
|
기본 동작
|
|
- 연결 타임아웃: 10초, 요청 타임아웃: 30초
|
|
- body가 있고 `Content-Type` 헤더가 없으면 자동으로 `application/json; charset=utf-8` 설정
|
|
- 예외 발생 시 `RuntimeException`으로 래핑하여 전달하며, `InterruptedException` 발생 시 인터럽트 플래그를 복원
|
|
|
|
응답 객체(`ExternalApiResponse`)
|
|
- 필드: `statusCode`(int), `headers`(Map<String, List<String>>), `body`(String)
|
|
- 정적 팩토리: `ExternalApiResponse.of(int, HttpHeaders, String)`
|
|
|
|
간단 사용 예시
|
|
|
|
```java
|
|
import com.kri.common.http.ExternalApiClient;
|
|
import com.kri.common.http.ExternalApiResponse;
|
|
import java.util.Map;
|
|
|
|
ExternalApiClient client = new ExternalApiClient();
|
|
|
|
// POST 예시
|
|
ExternalApiResponse postResp = client.post(
|
|
"https://api.example.com/items",
|
|
Map.of("X-API-KEY", "your-key"),
|
|
"{\"name\":\"sample\"}"
|
|
);
|
|
int status = postResp.getStatusCode();
|
|
String body = postResp.getBody();
|
|
|
|
// GET 예시
|
|
ExternalApiResponse getResp = client.get(
|
|
"https://api.example.com/items/123",
|
|
Map.of("Authorization", "Bearer token")
|
|
);
|
|
if (getResp.getStatusCode() == 200) {
|
|
System.out.println(getResp.getBody());
|
|
}
|
|
```
|
|
|
|
고급 사용: 커스텀 HttpClient/타임아웃
|
|
|
|
```java
|
|
import java.net.http.HttpClient;
|
|
import java.time.Duration;
|
|
|
|
HttpClient httpClient = HttpClient.newBuilder()
|
|
.connectTimeout(Duration.ofSeconds(5))
|
|
.build();
|
|
|
|
ExternalApiClient client = new ExternalApiClient(httpClient, Duration.ofSeconds(15));
|
|
```
|
|
|
|
주의사항
|
|
- 메서드 시그니처는 문자열 기반 body를 사용하므로, JSON 외 포맷을 전송할 경우 적절한 `Content-Type`을 직접 지정하세요.
|
|
- 대용량 응답이 예상된다면 현재 구현은 `BodyHandlers.ofString()`을 사용한다는 점에 유의하세요.
|
|
|
|
이 문서는 **KriCommon을 사용하는 서비스(`example-service`)** 기준으로 작성되었습니다.
|
|
(WebSocket 관련 기능은 현재 포함하지 않았으며, 추후 필요 시 별도 확장 예정입니다.)
|
|
|
|
---
|
|
|
|
## 빠른 시작(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.dto.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<String, String> 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<com.kri.common.auth.dto.JwtUserClaimsDto> findUserByApiKey(String apiKey) {
|
|
if ("DEMO-KEY-1234".equals(apiKey)) {
|
|
return java.util.Optional.of(
|
|
com.kri.common.auth.dto.JwtUserClaimsDto.builder()
|
|
.userId("external")
|
|
.userCmpn("outbound")
|
|
.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 예시 (권장)
|
|
|
|
`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 {
|
|
// 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=토큰값_여기에
|
|
```
|
|
|
|
> **주의**
|
|
> KriCommon은 `java-library` + `compileOnly` 위주로 구성되어 있어서
|
|
> **웹/시큐리티/Swagger/Redis Starter는 개별 서비스에서 직접 의존성을 추가**해야 합니다.
|
|
|
|
---
|
|
|
|
## 2. 자동 구성(AutoConfiguration) 개요
|
|
|
|
KriCommon은 다음 AutoConfiguration 들을 제공합니다.
|
|
모두 `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`에서 자동 등록됩니다.
|
|
|
|
| 클래스 | 역할 요약 |
|
|
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
|
|
| `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은 **프로퍼티로 on/off 가능**하며, 필요 시 서비스 쪽에서 Bean을 직접 정의하여 오버라이드 할 수 있습니다.
|
|
|
|
---
|
|
|
|
## 3. application.yml 예시
|
|
|
|
`example-service/src/main/resources/application.yml`:
|
|
|
|
```yaml
|
|
spring:
|
|
application:
|
|
name: example-service
|
|
|
|
datasource:
|
|
# (서비스에서 실제 DB 설정)
|
|
|
|
# Redis 사용 시 (선택)
|
|
data:
|
|
redis:
|
|
host: localhost
|
|
port: 6379
|
|
|
|
server:
|
|
port: 8080
|
|
|
|
logging:
|
|
file:
|
|
path: logs
|
|
level:
|
|
root: INFO
|
|
com.kri: DEBUG
|
|
|
|
# ===========================
|
|
# KRI 공통 설정
|
|
# ===========================
|
|
kri:
|
|
auth:
|
|
jwt:
|
|
secret: "서비스별_실제_시크릿키_32자_이상"
|
|
issuer: "kri-it"
|
|
access-token-validity-seconds: 86400 # 24시간
|
|
refresh-token-validity-seconds: 604800 # 7일
|
|
apikey:
|
|
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 # ErrorAdvice + TraceFilter
|
|
redis:
|
|
enabled: false # RedisQueueHelper (필요 시 true)
|
|
scheduling:
|
|
enabled: false # @EnableScheduling (필요 시 true)
|
|
```
|
|
|
|
---
|
|
|
|
## 4. 주요 기능 상세
|
|
|
|
### 4.1. JWT 설정 및 DTO (`com.kri.common.auth.jwt`)
|
|
|
|
#### 4.1.1. JwtProperties
|
|
|
|
```
|
|
@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
|
|
|
|
```
|
|
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 (사내 시스템 기준 PK)", example = "user123")
|
|
String userId;
|
|
|
|
@Schema(description = "사용자 팀/조직명", example = "IT팀")
|
|
String userTeam;
|
|
|
|
@Schema(description = "사용자 이름", example = "홍길동")
|
|
String userName;
|
|
|
|
@Schema(description = "권한 레벨 (int)", example = "1")
|
|
Integer role;
|
|
}
|
|
```
|
|
|
|
> `@Schema`가 붙어 있어서, Swagger UI 상에서도 필드 설명이 자연스럽게 노출됩니다.
|
|
|
|
#### 4.1.3. JwtService
|
|
|
|
주요 메서드:
|
|
|
|
```
|
|
public class JwtService {
|
|
|
|
// Access Token 생성 (DTO → JWT 문자열)
|
|
public String generateAccessToken(JwtUserClaimsDto userClaims);
|
|
|
|
// Refresh Token 생성
|
|
public String generateRefreshToken(String userId);
|
|
|
|
// 토큰 파싱 & 검증
|
|
public Claims getClaims(String token) throws JwtException;
|
|
public JwtUserClaimsDto toUserClaimsDto(String token) throws JwtException;
|
|
|
|
// Spring Security Authentication 변환
|
|
public Authentication toAuthentication(JwtUserClaimsDto dto);
|
|
public Authentication toAuthentication(String token) throws JwtException;
|
|
}
|
|
```
|
|
|
|
**로그인 예시**
|
|
|
|
```
|
|
@Service
|
|
@RequiredArgsConstructor
|
|
public class AuthService {
|
|
|
|
private final JwtService jwtService;
|
|
|
|
public String login(String username, String password) {
|
|
// 1) 서비스에서 사용자 검증 (DB 조회 등)
|
|
// 2) 검증 성공 시 공통 DTO 구성
|
|
JwtUserClaimsDto claims = JwtUserClaimsDto.builder()
|
|
.userId(username)
|
|
.userTeam("IT팀")
|
|
.userName("홍길동")
|
|
.role(1) // 권한 레벨
|
|
.build();
|
|
|
|
// 3) Access Token 발급
|
|
return jwtService.generateAccessToken(claims);
|
|
}
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
### 4.2. API Key 인증 (`com.kri.common.auth.apikey`)
|
|
|
|
#### 4.2.1. ApiKeyProperties
|
|
|
|
```
|
|
@ConfigurationProperties(prefix = "kri.auth.apikey")
|
|
public class ApiKeyProperties {
|
|
private boolean enabled = false;
|
|
private String headerName = "X-API-Key";
|
|
}
|
|
```
|
|
|
|
**프로퍼티 요약**
|
|
|
|
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
|
| ----------------------------- | ------- | ----------- | ----------------------- |
|
|
| `kri.auth.apikey.enabled` | boolean | `false` | API Key 인증 기능 사용 여부 |
|
|
| `kri.auth.apikey.header-name` | String | `X-API-Key` | API Key 를 읽을 HTTP 헤더 이름 |
|
|
|
|
#### 4.2.2. ApiKeyUserClaimsProvider (서비스 구현 필요)
|
|
|
|
```
|
|
public interface ApiKeyUserClaimsProvider {
|
|
|
|
/**
|
|
* API Key 로 사용자 정보를 조회한다.
|
|
*
|
|
* @param apiKey 요청 헤더에서 받은 API Key
|
|
* @return 유효한 키면 JwtUserClaimsDto, 아니면 Optional.empty()
|
|
*/
|
|
Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey);
|
|
}
|
|
```
|
|
|
|
**서비스 구현 예시 (`example-service`)**
|
|
|
|
```
|
|
@Component
|
|
@RequiredArgsConstructor
|
|
public class ExampleApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider {
|
|
|
|
@Override
|
|
public Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey) {
|
|
// 1) 사내 외부 파트너용 API Key 테이블 조회
|
|
// 2) 유효하면 JwtUserClaimsDto 로 매핑
|
|
if ("DEMO-KEY-1234".equals(apiKey)) {
|
|
return Optional.of(
|
|
JwtUserClaimsDto.builder()
|
|
.userId("external-partner")
|
|
.userTeam("External")
|
|
.userName("외부 파트너")
|
|
.role(9)
|
|
.build()
|
|
);
|
|
}
|
|
return Optional.empty();
|
|
}
|
|
}
|
|
```
|
|
|
|
#### 4.2.3. ApiKeyAuthFilter
|
|
|
|
`X-API-Key`(또는 설정된 헤더)로부터 API Key를 읽고,
|
|
`ApiKeyUserClaimsProvider`를 통해 사용자 정보를 조회한 뒤, `JwtService`를 사용해 `Authentication`을 세팅하는 필터입니다.
|
|
|
|
> 이 필터는 `JwtAutoConfiguration` / `KriSecurityAutoConfiguration`를 통해 **자동 Bean 등록**되고,
|
|
> `SecurityFilterChain`에서 JWT 필터보다 먼저 동작하도록 설정됩니다.
|
|
|
|
---
|
|
|
|
### 4.3. Security 기본 구성 (`com.kri.common.security`)
|
|
|
|
#### 4.3.1. KriSecurityProperties
|
|
|
|
```
|
|
@ConfigurationProperties(prefix = "kri.security")
|
|
public class KriSecurityProperties {
|
|
|
|
private boolean enabled = true;
|
|
|
|
// 인증 없이 허용할 URL 패턴들
|
|
private List<String> publicPaths = List.of(
|
|
"/v3/api-docs/**",
|
|
"/swagger-ui.html",
|
|
"/swagger-ui/**"
|
|
);
|
|
}
|
|
```
|
|
|
|
**프로퍼티 요약**
|
|
|
|
| 프로퍼티 | 타입 | 기본값 (일부) | 설명 |
|
|
| --------------------------- | ------------ | ---------------- | -------------------------- |
|
|
| `kri.security.enabled` | boolean | `true` | 공통 Security 자동 구성 사용 여부 |
|
|
| `kri.security.public-paths` | List<String> | 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` 순으로 필터 체인에 추가
|
|
|
|
**메소드 레벨 권한 예시**
|
|
|
|
```
|
|
@org.springframework.web.bind.annotation.RestController
|
|
@org.springframework.web.bind.annotation.RequestMapping("/api/example")
|
|
public class ExampleController {
|
|
|
|
// 누구나 접근 가능하게 열고 싶다면:
|
|
@jakarta.annotation.security.PermitAll
|
|
@org.springframework.web.bind.annotation.GetMapping("/public")
|
|
public String publicApi() {
|
|
return "ok";
|
|
}
|
|
|
|
// 특정 권한 레벨 사용 (예: ROLE_1)
|
|
@org.springframework.security.access.prepost.PreAuthorize("hasRole('1')")
|
|
@org.springframework.web.bind.annotation.GetMapping("/admin-only")
|
|
public String adminOnly() {
|
|
return "admin";
|
|
}
|
|
}
|
|
```
|
|
|
|
> `@PermitAll` / `@PreAuthorize` 사용이 가능하며,
|
|
> URL 패턴 기반 예외 처리는 `kri.security.public-paths` 로 관리합니다.
|
|
|
|
---
|
|
|
|
### 4.4. Swagger / OpenAPI (`com.kri.common.swagger`)
|
|
|
|
#### 4.4.1. KriSwaggerProperties
|
|
|
|
```
|
|
@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
|
|
|
|
```
|
|
@AutoConfiguration
|
|
@EnableConfigurationProperties(KriIpAccessProperties.class)
|
|
@ConditionalOnProperty(prefix = "kri.webmvc", name = "enabled", havingValue = "true", matchIfMissing = true)
|
|
@RequiredArgsConstructor
|
|
public class KriWebMvcAutoConfiguration {
|
|
|
|
@Bean
|
|
@ConditionalOnMissingBean
|
|
public IpAccessControlService ipAccessControlService(KriIpAccessProperties props) {
|
|
return new IpAccessControlService(props);
|
|
}
|
|
|
|
@Bean
|
|
@ConditionalOnMissingBean
|
|
public IpAccessControlInterceptor ipAccessControlInterceptor(IpAccessControlService svc) {
|
|
return new IpAccessControlInterceptor(svc);
|
|
}
|
|
|
|
@Bean
|
|
public WebMvcConfigurer kriWebMvcConfigurer(ObjectProvider<IpAccessControlInterceptor> 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/**")
|
|
);
|
|
}
|
|
};
|
|
}
|
|
}
|
|
```
|
|
|
|
#### 4.5.2. KriIpAccessProperties & IP 설정
|
|
|
|
```
|
|
@ConfigurationProperties(prefix = "kri.webmvc.ip")
|
|
public class KriIpAccessProperties {
|
|
|
|
private final List<String> 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<String> additionalCidrs = new ArrayList<>();
|
|
|
|
public List<String> getEffectiveCidrs() {
|
|
return Stream.concat(defaultCidrs.stream(), additionalCidrs.stream())
|
|
.distinct()
|
|
.collect(Collectors.toList());
|
|
}
|
|
}
|
|
```
|
|
|
|
**프로퍼티 요약**
|
|
|
|
| 프로퍼티 | 타입 | 설명 |
|
|
| -------------------------------- | ------------ | --------------------------------- |
|
|
| `kri.webmvc.enabled` | boolean | CORS 및 Swagger IP 제어 자동 구성 on/off |
|
|
| `kri.webmvc.ip.additional-cidrs` | List<String> | 기본 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
|
|
|
|
```
|
|
@org.springframework.boot.autoconfigure.AutoConfiguration
|
|
@org.springframework.boot.autoconfigure.condition.ConditionalOnProperty(name = "common.web.enabled", matchIfMissing = true)
|
|
public class CommonWebAutoConfiguration {
|
|
|
|
@org.springframework.context.annotation.Bean
|
|
public com.kri.common.web.ErrorAdvice errorAdvice() {
|
|
// 예시 코드: 실제 라이브러리에서는 구현되어 있으므로, 서비스에서는 별도 정의 불필요
|
|
return null;
|
|
}
|
|
|
|
@org.springframework.context.annotation.Bean
|
|
public org.springframework.boot.web.servlet.FilterRegistrationBean<com.kri.common.web.TraceFilter> traceFilter() {
|
|
// 예시 코드: 실제 라이브러리에서는 구현되어 있으므로, 서비스에서는 별도 정의 불필요
|
|
return null;
|
|
}
|
|
}
|
|
```
|
|
|
|
* `ErrorAdvice`: `@RestControllerAdvice` 형태의 글로벌 예외 처리
|
|
* `TraceFilter`: HTTP 요청마다 `X-Request-Id` 및 MDC `traceId` 설정
|
|
* 추가로 MDC 핸들러/Service AOP를 통해 로그에 handler/service 정보 포함
|
|
|
|
---
|
|
|
|
### 4.6. Redis 큐 (`com.kri.common.redis`)
|
|
|
|
#### 4.6.1. CommonRedisAutoConfiguration
|
|
|
|
```
|
|
@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 {
|
|
|
|
@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);
|
|
}
|
|
|
|
@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);
|
|
}
|
|
}
|
|
```
|
|
|
|
**프로퍼티**
|
|
|
|
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
|
| ---------------------- | ------- | ----- | ---------------------- |
|
|
| `common.redis.enabled` | boolean | false | RedisQueueHelper 사용 여부 |
|
|
|
|
#### 4.6.2. RedisQueueHelper 사용 예시
|
|
|
|
```
|
|
@Service
|
|
@RequiredArgsConstructor
|
|
public class ExportQueueService {
|
|
|
|
private final RedisQueueHelper redisQueueHelper;
|
|
|
|
public void pushJob(String jobJson) {
|
|
redisQueueHelper.push("export:jobs", jobJson);
|
|
}
|
|
|
|
public String popJob() {
|
|
return redisQueueHelper.pop("export:jobs");
|
|
}
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
### 4.7. 스케줄링 (`com.kri.common.scheduling`)
|
|
|
|
```
|
|
@AutoConfiguration
|
|
@EnableScheduling
|
|
@ConditionalOnProperty(prefix = "common.scheduling", name = "enabled", havingValue = "true")
|
|
public class CommonSchedulingAutoConfiguration { }
|
|
```
|
|
|
|
**프로퍼티**
|
|
|
|
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
|
| --------------------------- | ------- | ----- | -------------------------- |
|
|
| `common.scheduling.enabled` | boolean | false | `@EnableScheduling` 활성화 여부 |
|
|
|
|
서비스 쪽에서는 단순히:
|
|
|
|
```yaml
|
|
common:
|
|
scheduling:
|
|
enabled: true
|
|
```
|
|
|
|
만 지정하면, `@Scheduled` 애노테이션을 사용할 수 있습니다.
|
|
|
|
---
|
|
|
|
### 4.8. 로그 설정 (`logback-spring.xml`)
|
|
|
|
* `app.name` (없으면 기본값 `app`)
|
|
* `logging.file.path` (없으면 `logs`)
|
|
|
|
을 활용해서 로그 디렉토리와 패턴을 설정합니다.
|
|
|
|
`traceId`, `handler`, `service` 등 MDC 정보가 포함된 공통 패턴을 사용하도록 되어 있으며,
|
|
서비스에서 별도의 `logback-spring.xml`을 두면 그 설정이 우선합니다.
|
|
|
|
---
|
|
|
|
### 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<String, Object> 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<String, Object> 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<String,Object>) 시그니처가 존재합니다.
|
|
|
|
#### 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. **의존성 추가**
|
|
|
|
* Spring Boot Web / Security / Validation / (필요시) Redis / Swagger
|
|
* `implementation "com.kri.common:starter:1.0.11"`
|
|
|
|
2. **application.yml 구성**
|
|
|
|
* `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
|
|
|
|
3. **로그인 엔드포인트 구현**
|
|
|
|
* 사용자 검증 후 `JwtUserClaimsDto`를 만들어 `JwtService.generateAccessToken()` 호출
|
|
* Controller에서 JWT를 응답으로 내려줌
|
|
|
|
4. **외부 API Key 사용 시**
|
|
|
|
* `ApiKeyUserClaimsProvider` 구현체를 Bean으로 등록
|
|
* `kri.auth.apikey.enabled=true` 설정
|
|
|
|
5. **권한 제어**
|
|
|
|
* URL 레벨: `kri.security.public-paths` (기본 + 추가)
|
|
* 메소드 레벨: `@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 기준) |