940 lines
32 KiB
Markdown
940 lines
32 KiB
Markdown
# KriCommon 설정/기능 정리
|
|
|
|
KriCommon은 KRI 계열 Spring Boot 서비스에서 반복해서 쓰는 인증, 보안, 웹, Swagger, Redis, Excel, JSON, 날짜/시간, JPA 보조 기능을 모은 Java 17 라이브러리입니다.
|
|
|
|
라이브러리의 패키지는 역할에 따라 다음 4개 축으로 나뉩니다.
|
|
|
|
- `com.kri.common.autoconfigure`: Spring Boot 자동 구성과 `@ConfigurationProperties`
|
|
- `com.kri.common.feature`: 서비스 코드가 직접 import해서 쓰는 공개 기능
|
|
- `com.kri.common.runtime`: 자동 구성으로 조립되는 필터, 컨버터, 어드바이스 등 내부 실행 요소
|
|
- `com.kri.common.endpoint`: 설정에 따라 노출되는 공통 관리 API
|
|
|
|
설정 prefix는 `kri.*`만 사용합니다.
|
|
|
|
---
|
|
|
|
## 빌드와 배포
|
|
|
|
- Java: 17
|
|
- Gradle plugins: `java-library`, `maven-publish`
|
|
- Group: `com.kri.common`
|
|
- Artifact: `starter`
|
|
- Version: `build.gradle`의 `commonVer`
|
|
- Spring Boot BOM: `org.springframework.boot:spring-boot-dependencies:3.5.7`
|
|
- Publish target: Gitea Maven Packages
|
|
|
|
```bash
|
|
./gradlew compileJava
|
|
./gradlew publishReleasePublicationToGiteaRepository
|
|
```
|
|
|
|
배포 전에 `checkGiteaPackageVersionNotExists` 태스크가 같은 Maven package version이 이미 있는지 확인합니다. Gitea 인증은 Gradle property `giteaUser`, `giteaToken` 또는 환경 변수 `GITEA_USER`, `GITEA_TOKEN`을 사용합니다.
|
|
|
|
---
|
|
|
|
## 의존성 성격
|
|
|
|
이 라이브러리는 starter 형태지만 모든 런타임 의존성을 강제로 끌어오지 않습니다. 서비스가 실제로 쓰는 기능에 맞춰 Spring Boot starter를 함께 선언해야 합니다.
|
|
|
|
- JWT: `jjwt-api`, `jjwt-impl`, `jjwt-jackson`
|
|
- Security core: `spring-security-core`
|
|
- Security web/config: compileOnly
|
|
- Spring Web, Validation, AOP, Redis, JPA, Autoconfigure: compileOnly
|
|
- Swagger/OpenAPI: compileOnly
|
|
- JSON: Jackson Databind
|
|
- Excel: Apache POI
|
|
- Lombok: compileOnly/annotationProcessor
|
|
|
|
예를 들어 보안 필터 체인을 쓰는 서비스는 Spring Security Web/Config가 classpath에 있어야 하고, Swagger 자동 구성을 쓰는 서비스는 springdoc이 classpath에 있어야 합니다.
|
|
|
|
---
|
|
|
|
## 직접 import해서 쓰는 기능
|
|
|
|
### 인증/JWT
|
|
|
|
#### `JwtService`
|
|
|
|
```java
|
|
import com.kri.common.feature.auth.jwt.JwtService;
|
|
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
|
|
```
|
|
|
|
JWT 발급, 파싱, claims 변환, Spring Security `Authentication` 변환을 담당합니다.
|
|
|
|
주요 메서드:
|
|
|
|
- `generateAccessToken(JwtUserClaimsDto userClaims)`
|
|
- `generateRefreshToken(String userId)`
|
|
- `parseToken(String token)`
|
|
- `getClaims(String token)`
|
|
- `toUserClaimsDto(Claims claims)`
|
|
- `toUserClaimsDto(String token)`
|
|
- `toAuthentication(JwtUserClaimsDto dto)`
|
|
- `toAuthentication(String token)`
|
|
|
|
`JwtUserClaimsDto`에 포함되는 필드는 `userId`, `userCmpn`, `userTeam`, `userName`, `userRole`입니다.
|
|
|
|
#### `ApiKeyUserClaimsProvider`
|
|
|
|
```java
|
|
import com.kri.common.feature.auth.apikey.ApiKeyUserClaimsProvider;
|
|
```
|
|
|
|
API Key를 `JwtUserClaimsDto`로 매핑하는 확장 인터페이스입니다.
|
|
|
|
```java
|
|
Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey);
|
|
```
|
|
|
|
서비스에서 직접 구현한 Bean을 등록하거나, `kri.auth.apikey.enabled=true`와 JPA 관련 classpath/설정을 통해 DB preload 기반 provider를 사용할 수 있습니다.
|
|
|
|
### 요청 사용자 컨텍스트
|
|
|
|
#### `RequestUserContext`
|
|
|
|
```java
|
|
import com.kri.common.feature.web.RequestUserContext;
|
|
```
|
|
|
|
컨트롤러 파라미터로 선언하면 현재 인증 사용자와 client IP를 받을 수 있습니다. `JwtService` Bean이 있을 때 `RequestUserContextArgumentResolver`가 자동 등록됩니다.
|
|
|
|
Swagger 자동 구성이 활성화되면 `RequestUserContext`는 요청 입력 문서에서 제외됩니다. `authenticated`, `clientIp`, `userRole` 등의 입력 항목은 표시되지 않으며, 실제 요청의 인증 정보와 IP 주입 동작은 유지됩니다.
|
|
|
|
```java
|
|
@GetMapping("/me")
|
|
public Object me(RequestUserContext user) {
|
|
return user;
|
|
}
|
|
```
|
|
|
|
필드는 `userId`, `userCmpn`, `userTeam`, `userName`, `userRole`, `clientIp`이며, `isAuthenticated()`는 `userId != null`일 때 `true`를 반환합니다.
|
|
|
|
### 예외/페이징
|
|
|
|
#### `BusinessException`
|
|
|
|
서비스 레이어에서 HTTP 상태, 에러 코드, 메시지, 부가 정보를 함께 담아 던지는 런타임 예외입니다.
|
|
|
|
```java
|
|
throw BusinessException.badRequest("INVALID_INPUT", "입력값이 올바르지 않습니다.");
|
|
```
|
|
|
|
팩토리 메서드:
|
|
|
|
- `badRequest`
|
|
- `unauthorized`
|
|
- `forbidden`
|
|
- `notFound`
|
|
- `conflict`
|
|
- `validationError`
|
|
- `internalError`
|
|
- `of`
|
|
|
|
`with(String key, Object value)`로 응답에 포함할 부가 정보를 추가할 수 있습니다.
|
|
|
|
#### `PageRequestDto`, `Pageables`, `PageResponseDto`
|
|
|
|
```java
|
|
Pageable pageable = Pageables.of(req, ProjectEntity.class);
|
|
PageResponseDto<ProjectDto> response = PageResponseDto.from(page);
|
|
```
|
|
|
|
`PageRequestDto` 기본값:
|
|
|
|
- `pageIndex = 0`
|
|
- `pageSize = 10`
|
|
- `sortBy = "prjctIdx"`
|
|
- `sortDir = "desc"`
|
|
|
|
`Pageables.of`는 정렬 필드가 대상 클래스에 존재하는지 검증한 뒤 `Pageable`을 생성합니다.
|
|
|
|
### Redis
|
|
|
|
#### `RedisQueueHelper`
|
|
|
|
```java
|
|
import com.kri.common.feature.redis.RedisQueueHelper;
|
|
```
|
|
|
|
`StringRedisTemplate` 기반 Redis List 큐 helper입니다.
|
|
|
|
- `enqueue(String key, String value)`
|
|
- `blockingDequeue(String key, Duration timeout)`
|
|
|
|
`kri.redis.enabled=true`이고 `RedisConnectionFactory`가 있으면 자동 등록됩니다.
|
|
|
|
### HTTP
|
|
|
|
#### `ExternalApiClient`, `ExternalApiResponse`
|
|
|
|
JDK `HttpClient` 기반 경량 HTTP client입니다.
|
|
|
|
```java
|
|
ExternalApiClient client = new ExternalApiClient();
|
|
ExternalApiResponse res = client.post(url, headers, jsonBody);
|
|
```
|
|
|
|
`ExternalApiMultipartPart`를 사용해 `multipart/form-data` 업로드를 전송할 수 있습니다.
|
|
|
|
```java
|
|
List<ExternalApiMultipartPart> parts = List.of(
|
|
ExternalApiMultipartPart.formField("serviceCode", "demo"),
|
|
ExternalApiMultipartPart.file("file", "한글-파일.txt", "text/plain", fileBytes)
|
|
);
|
|
|
|
ExternalApiResponse res = client.postMultipart(url, headers, parts);
|
|
```
|
|
|
|
multipart 요청에서는 전달한 headers의 `Content-Type` 값을 무시하고, 필요한 boundary를 포함한
|
|
`Content-Type: multipart/form-data; boundary=...` 값을 자동 생성합니다.
|
|
multipart 파트 헤더와 텍스트 필드는 UTF-8로 인코딩하고, 파일 내용은 원본
|
|
`byte[]`로 전송합니다. ASCII와 non-ASCII 파일명 모두 원본 값을 quoted `filename`에
|
|
UTF-8 바이트로 전송하며, ASCII fallback이나 `filename*`는 추가하지 않습니다.
|
|
|
|
```http
|
|
Content-Disposition: form-data; name="file"; filename="한글-파일.txt"
|
|
```
|
|
|
|
지원 메서드:
|
|
|
|
- `get`
|
|
- `delete`
|
|
- `post`
|
|
- `put`
|
|
- `patch`
|
|
- `postMultipart`
|
|
- `putMultipart`
|
|
|
|
응답은 `statusCode`, `headers`, `body`를 제공합니다.
|
|
|
|
`getBody()`는 기존처럼 `Content-Type`의 charset(없거나 알 수 없으면 UTF-8)으로
|
|
해석한 문자열을 반환하며, `getBodyBytes()`는 수신한 원본 바이트의 복사본을 반환합니다.
|
|
charset 추출 시 다른 매개변수의 따옴표 내부 문자열은 charset 선언으로 취급하지 않습니다.
|
|
직접 호출도 오류에서 후속 작업을 중단하려면 `requireSuccess()`를 사용합니다.
|
|
|
|
```java
|
|
ExternalApiResponse response = client.put(url, headers, json).requireSuccess();
|
|
String bulkSendKey = response.getBody();
|
|
```
|
|
|
|
`requireSuccess()`는 2xx에서 같은 응답을 반환하고, 그 외 상태에서는
|
|
`com.kri.common.feature.http.ExternalApiResponseException`을 던집니다.
|
|
기존 호출은 명시적으로 검증하지 않으면 오류 상태도 응답 객체로 반환합니다.
|
|
|
|
#### `BypassClient`
|
|
|
|
Front에서 들어온 요청을 target API로 bypass하는 HTTP client입니다. 원본 method, query param,
|
|
header, body를 기반으로 target URL만 재조립하고, target 응답의 status/header/body bytes를
|
|
`BypassResponse`로 반환합니다. 응답 controller에서는 `ResponseEntity<byte[]>`로 내려주면
|
|
front는 `Content-Type`에 따라 JSON, text, blob 등을 처리할 수 있습니다.
|
|
|
|
패키지:
|
|
|
|
```java
|
|
import com.kri.common.feature.http.bypass.BypassClient;
|
|
import com.kri.common.feature.http.bypass.BypassForwardOptions;
|
|
import com.kri.common.feature.http.bypass.BypassRequestCustomizer;
|
|
import com.kri.common.feature.http.bypass.BypassResponse;
|
|
import com.kri.common.feature.http.bypass.BypassResponseCustomizer;
|
|
```
|
|
|
|
설정 예:
|
|
|
|
```yaml
|
|
kri:
|
|
http:
|
|
bypass:
|
|
enabled: true
|
|
targets:
|
|
nice:
|
|
base-url: https://api.nice.example
|
|
strip-prefix: /api/bypass/nice
|
|
allowed-paths:
|
|
- /v1/**
|
|
request-customizers:
|
|
- niceAuthCustomizer
|
|
response-customizers:
|
|
- niceResponseCustomizer
|
|
```
|
|
|
|
Controller 예:
|
|
|
|
```java
|
|
@RestController
|
|
@RequestMapping("/api/bypass/nice")
|
|
public class NiceBypassController {
|
|
|
|
private final BypassClient bypassClient;
|
|
|
|
public NiceBypassController(BypassClient bypassClient) {
|
|
this.bypassClient = bypassClient;
|
|
}
|
|
|
|
@RequestMapping("/**")
|
|
public ResponseEntity<byte[]> bypass(
|
|
HttpServletRequest request,
|
|
@RequestBody(required = false) byte[] body
|
|
) {
|
|
BypassResponse response = bypassClient.forward("nice", request, body);
|
|
|
|
return ResponseEntity
|
|
.status(response.statusCode())
|
|
.headers(response.httpHeaders())
|
|
.body(response.body());
|
|
}
|
|
}
|
|
```
|
|
|
|
Target별 request/response customizer는 소비 서비스에서 Bean으로 등록하고,
|
|
`application.yml`의 customizer bean name 목록에 연결합니다.
|
|
|
|
```java
|
|
@Bean
|
|
BypassRequestCustomizer niceAuthCustomizer() {
|
|
return (request, context) -> request.toBuilder()
|
|
.header("Authorization", "Bearer ${token}")
|
|
.queryParam("clientId", "contact")
|
|
.build();
|
|
}
|
|
|
|
@Bean
|
|
BypassResponseCustomizer niceResponseCustomizer() {
|
|
return (response, context) -> response.toBuilder()
|
|
.header("X-Bypass-Target", context.targetName())
|
|
.build();
|
|
}
|
|
```
|
|
|
|
요청 1회성 customizer도 `BypassForwardOptions`로 추가할 수 있습니다. 적용 순서는
|
|
target 설정 customizer가 먼저이고, per-request customizer가 마지막입니다.
|
|
|
|
```java
|
|
BypassResponse response = bypassClient.forward(
|
|
"nice",
|
|
request,
|
|
body,
|
|
BypassForwardOptions.builder()
|
|
.attribute("loginUserId", user.userId())
|
|
.requestCustomizer((bypassRequest, context) -> bypassRequest.toBuilder()
|
|
.header("X-User-Id", context.attribute("loginUserId", String.class))
|
|
.build())
|
|
.responseCustomizer((bypassResponse, context) -> bypassResponse.toBuilder()
|
|
.header("X-Handled-By", "contact-server")
|
|
.build())
|
|
.build()
|
|
);
|
|
```
|
|
|
|
보안상 front가 full target URL을 직접 넘기지 않게 하고, controller에서는 `targetName`을 서버
|
|
코드로 고정하는 것을 권장합니다. `allowed-paths`로 호출 가능한 path를 제한하고, 원본 요청의
|
|
`Host`, `Content-Length`, `Transfer-Encoding`, `Connection` 같은 hop-by-hop header는
|
|
전달하지 않습니다.
|
|
|
|
HTTP/2 전용 `:status` 등 `:`로 시작하는 헤더도 전달하지 않습니다. 상태값은
|
|
`BypassResponse.statusCode()`를 사용하며 일반 응답 헤더와 원본 바디는 유지합니다.
|
|
|
|
#### 원본 오류 응답 전달
|
|
|
|
대상별 `throw-on-error`의 기본값은 `false`이며, 기존처럼 비정상 HTTP 상태도
|
|
`BypassResponse`로 반환합니다. 내부 서비스 처리에서 오류 이후 실행을 중단하려면
|
|
해당 대상에만 활성화할 수 있습니다.
|
|
|
|
```yaml
|
|
kri:
|
|
http:
|
|
bypass:
|
|
enabled: true
|
|
targets:
|
|
nice:
|
|
base-url: https://api.nice.example
|
|
allowed-paths:
|
|
- /v1/**
|
|
throw-on-error: true
|
|
```
|
|
|
|
활성화하면 응답 customizer 적용 후 최종 상태가 2xx가 아닐 때
|
|
`ExternalApiResponseException`을 던집니다. 호출별 명시적 검증은
|
|
`bypassClient.forward(...).requireSuccess()`로도 가능합니다. 연결 실패는 기존
|
|
`BYPASS_CALL_FAILED` 처리이며, 원본 HTTP 응답이 없는 경우와 구분합니다.
|
|
response customizer 안에서 `requireSuccess()`를 호출하거나 `ExternalApiResponseException`을
|
|
던지면 그 예외를 그대로 전파합니다. 일반 customizer 실패는 기존 오류 처리를 유지합니다.
|
|
|
|
Spring MVC와 Servlet API가 있고 `kri.web.enabled=true`(기본값)이면
|
|
`ExternalApiErrorAutoConfiguration`이 원본 응답 처리기를 자동 등록합니다.
|
|
원본 HTTP 상태와 바디 바이트, `Content-Type`, `Content-Encoding`을 그대로 반환하므로
|
|
상위 서비스의 오류 필드와 압축된 바디를 유지합니다. 쿠키·인증·전송 헤더는 오류
|
|
처리기가 전달하지 않습니다. 오류 바디가 비어 있으면 빈 바디를 그대로 반환합니다.
|
|
|
|
공통 처리기는 이 전용 예외만 처리하며 일반 공통 오류 처리보다 먼저 적용됩니다.
|
|
소비 서비스가 `externalApiResponseAdvice`라는 이름으로 자체 오류 처리기 Bean을
|
|
제공하면 기본 등록을 대체할 수 있으며 runtime 구현에 의존할 필요가 없습니다.
|
|
예외를 컨트롤러에서 명시적으로 처리할 수도 있습니다. Web이 비활성화되었거나 없는 환경에서는
|
|
직접 예외를 처리해야 합니다. 원본 오류 바디의 외부 노출이 적절한 대상에만 활성화하세요.
|
|
|
|
### 암호화와 해시
|
|
|
|
공개 API는 `com.kri.common.feature.crypto.*`에 있습니다. 중앙 키 DB를 사용하지 않으며,
|
|
AES master key는 `kri.crypto.aes.keys` 설정 또는 각 호출의 `masterKey`로 전달합니다.
|
|
|
|
#### AES-256
|
|
|
|
기본 알고리즘은 인증 암호화인 `AES_256_GCM`입니다. `masterKey`와 salt를
|
|
`PBKDF2WithHmacSHA256`으로 처리해 256-bit AES key를 만들며, salt와 IV를 생략하면
|
|
안전한 난수로 자동 생성합니다. 기존 시스템 연동을 위해 salt와 IV를 직접 전달할 수도 있습니다.
|
|
|
|
```java
|
|
import com.kri.common.feature.crypto.aes.AesCryptoService;
|
|
import com.kri.common.feature.crypto.aes.AesDecryptRequest;
|
|
import com.kri.common.feature.crypto.aes.AesEncryptRequest;
|
|
import com.kri.common.feature.crypto.aes.AesEncryptedValue;
|
|
import com.kri.common.feature.crypto.aes.AesEncryptedValueCodec;
|
|
import com.kri.common.feature.crypto.aes.TagLayout;
|
|
|
|
AesEncryptedValue encrypted = aesCryptoService.encrypt(
|
|
AesEncryptRequest.builder(plainBytes)
|
|
.masterKey(masterKey)
|
|
.salt(salt)
|
|
.iv(iv)
|
|
.aad(aad)
|
|
.tagLayout(TagLayout.DETACHED)
|
|
.build()
|
|
);
|
|
|
|
String storedValue = AesEncryptedValueCodec.encode(encrypted);
|
|
AesEncryptedValue decoded = AesEncryptedValueCodec.decode(storedValue);
|
|
byte[] restored = aesCryptoService.decrypt(
|
|
AesDecryptRequest.builder(decoded)
|
|
.masterKey(masterKey)
|
|
.aad(aad)
|
|
.build()
|
|
);
|
|
```
|
|
|
|
- GCM tag는 ciphertext 결합형 `APPENDED` 또는 별도 필드형 `DETACHED`를 지원합니다.
|
|
- GCM tag는 생략할 수 없습니다. tag가 없는 기존 데이터는 명시적으로
|
|
`AES_256_CBC_PKCS5`를 선택해야 하며, CBC는 변조를 감지하지 못하므로 신규 데이터에 권장하지 않습니다.
|
|
- GCM IV는 12바이트, CBC IV는 16바이트이고 salt는 최소 16바이트입니다.
|
|
- 호출자가 IV를 직접 전달하면 동일한 key에서 IV가 중복되지 않도록 호출 서비스가 보장해야 합니다.
|
|
- AAD는 GCM에서만 지원하며 복호화할 때 암호화 시점과 동일한 값을 전달해야 합니다.
|
|
- 암호화 결과는 format version, algorithm, key ID, KDF iteration, salt, IV, ciphertext 및 tag 정보를 포함합니다.
|
|
|
|
#### 일반 digest와 BCrypt
|
|
|
|
```java
|
|
import com.kri.common.feature.crypto.hash.AdaptiveHashService;
|
|
import com.kri.common.feature.crypto.hash.DigestAlgorithm;
|
|
import com.kri.common.feature.crypto.hash.DigestEncoding;
|
|
import com.kri.common.feature.crypto.hash.DigestService;
|
|
|
|
String checksum = digestService.digest(
|
|
bytes,
|
|
DigestAlgorithm.SHA_256,
|
|
DigestEncoding.HEX_LOWER
|
|
);
|
|
|
|
String encodedSecret = adaptiveHashService.hash("secret-value");
|
|
boolean matched = adaptiveHashService.matches("secret-value", encodedSecret);
|
|
```
|
|
|
|
`DigestService`는 MD5, SHA-1, SHA-256, SHA-512와 HEX 소문자/대문자, Base64 출력을 지원합니다.
|
|
MD5와 SHA-1 enum 이름은 각각 `MD5_LEGACY`, `SHA_1_LEGACY`이며 기존 데이터 검증과
|
|
연동에만 사용해야 합니다. `AdaptiveHashService`는 BCrypt 기반이며 비밀번호뿐 아니라 PIN,
|
|
복구 코드, API Secret 같은 짧은 비밀값 검증에 사용할 수 있습니다. BCrypt 결과에는 salt가
|
|
포함되며 일반적인 구현의 72바이트 입력 제한을 고려해야 합니다.
|
|
|
|
### JSON
|
|
|
|
#### `JsonUtil`
|
|
|
|
Jackson `ObjectMapper`를 명시적으로 받아 JSON 변환을 수행하는 static helper입니다.
|
|
|
|
- `toMap`
|
|
- `parseJsonToMap`
|
|
- `toJson`
|
|
- `toPrettyJson`
|
|
- `fromJson`
|
|
- `deepCopy`
|
|
- `convert`
|
|
|
|
### Excel
|
|
|
|
#### `ExcelColumn`
|
|
|
|
DTO 필드와 Excel 컬럼을 매핑하는 애너테이션입니다.
|
|
|
|
```java
|
|
@ExcelColumn(header = "사용자 ID", order = 1, width = 20)
|
|
private String userId;
|
|
```
|
|
|
|
- `header`: Excel 헤더명
|
|
- `order`: 컬럼 순서
|
|
- `width`: 문자 폭 기준 너비, `-1`이면 기본 auto size 흐름 사용
|
|
|
|
#### `ExcelMapper`
|
|
|
|
Apache POI 기반 Excel 읽기/쓰기 helper입니다.
|
|
|
|
주요 기능:
|
|
|
|
- DTO 리스트를 `Workbook`으로 쓰기
|
|
- `Workbook`을 DTO 리스트로 읽기
|
|
- `Map<String, ?>` 리스트를 Excel로 쓰기
|
|
- Excel을 `List<Map<String, String>>`으로 읽기
|
|
- `SXSSFWorkbook` 기반 대용량 스트리밍 쓰기
|
|
- SAX 기반 대용량 스트리밍 읽기
|
|
- streaming writer를 열어 row를 점진적으로 append
|
|
|
|
`Path`를 받는 `readStreaming`과 `readHeaderStreaming`은 `PackageAccess.READ`로 파일을 열어 원본의 SHA-256, 크기, 수정 시각을 유지합니다. 읽기 전용 파일도 처리하며, 콜백에서 예외가 발생해도 원본을 저장하지 않고 파일 핸들을 해제합니다. 기존 옵션 검증, 예외 처리, SAX 스트리밍 방식은 유지합니다.
|
|
|
|
#### `StreamingReadOptions`
|
|
|
|
스트리밍 읽기 옵션입니다.
|
|
|
|
- `sheetName`
|
|
- `sheetIndex`
|
|
- `headerRowIndex`
|
|
- `headerNormalizer`
|
|
|
|
기본값은 첫 번째 sheet, header row index `1`, header normalizer identity입니다.
|
|
|
|
### 날짜/시간
|
|
|
|
#### `DateTimeUtil`
|
|
|
|
KST/UTC 기준 날짜 시간 변환 helper입니다.
|
|
|
|
주요 기능:
|
|
|
|
- 현재 KST 날짜/시간 반환
|
|
- `Instant`를 KST 문자열, `ZonedDateTime`, `LocalDateTime`, `LocalDate`로 변환
|
|
- `yyyy-MM-dd`, `yyyy-MM-dd HH:mm:ss`, ISO datetime 형식 검증
|
|
- 문자열을 `Instant`, `LocalDate`, `LocalDateTime`으로 파싱
|
|
|
|
#### `LenientLocalDateTime`
|
|
|
|
Jackson 역직렬화에서 여러 날짜/시간 입력을 허용하기 위한 필드 애너테이션입니다. 내부적으로 `LenientLocalDateTimeDeserializer`를 사용합니다.
|
|
|
|
### Enum
|
|
|
|
#### `CodeEnum<T>`, `CodeEnumUtils`
|
|
|
|
코드값을 갖는 enum의 공통 인터페이스와 변환 helper입니다.
|
|
|
|
```java
|
|
public enum Status implements CodeEnum<String> {
|
|
ACTIVE("A");
|
|
|
|
private final String code;
|
|
|
|
@Override
|
|
public String getCode() {
|
|
return code;
|
|
}
|
|
}
|
|
|
|
Status status = CodeEnumUtils.fromCode(Status.class, "A");
|
|
```
|
|
|
|
웹 자동 구성은 request parameter/path variable의 문자열 값을 `CodeEnum` 구현 enum으로 변환하는 `CodeEnumConverter`를 등록합니다. Swagger 자동 구성은 `CodeEnum` schema/parameter 설명도 보강합니다.
|
|
|
|
### JPA
|
|
|
|
#### `AbstractCodeEnumConverter`
|
|
|
|
JPA `AttributeConverter` 구현을 쉽게 만들기 위한 추상 클래스입니다.
|
|
|
|
#### `BaseUuidEntity`
|
|
|
|
UUID 기반 JPA base entity입니다.
|
|
|
|
#### `EntityColumnAccessor`
|
|
|
|
JPA `@Column(name = "...")` 기준으로 entity 필드를 읽고 쓰는 reflection helper입니다.
|
|
|
|
- `get`
|
|
- `set`
|
|
- `setForInsert`
|
|
- `setForUpdate`
|
|
|
|
### Cache base class
|
|
|
|
#### `AbstractMapCache<K, V>`, `AbstractListCache<T>`
|
|
|
|
메모리 캐시 구현을 위한 base class입니다. 구현체는 데이터를 로딩하는 protected 메서드를 구현하고, 필요 시 `loadOnStartup`, `reload`, `clear`, `put/add` 계열 메서드를 사용합니다.
|
|
|
|
### File/String/Number/Common utility
|
|
|
|
#### `FileUtil`
|
|
|
|
- `sanitizeFileName`
|
|
- `getExtension`
|
|
- `extractFileNameFromPath`
|
|
|
|
#### `StringUtil`
|
|
|
|
- null/blank 검사
|
|
- 이메일/숫자 정규화
|
|
- 기본 텍스트/이메일 형식 검사
|
|
- HTML, JSON, CSV, Excel formula escape
|
|
|
|
#### `NumericUtil`
|
|
|
|
- numeric 문자열 검사
|
|
- short/int/long 안전 파싱
|
|
- 숫자만 추출해 `Integer`로 파싱
|
|
|
|
#### `CollectionUtil`
|
|
|
|
- `Map`, `Collection` empty 검사
|
|
|
|
#### `CommonUtil`
|
|
|
|
- UUID 문자열 생성
|
|
|
|
---
|
|
|
|
## yml로 설정하는 자동 구성
|
|
|
|
### 전체 예시
|
|
|
|
```yaml
|
|
kri:
|
|
auth:
|
|
jwt:
|
|
secret: "replace-with-service-secret-at-least-32-bytes"
|
|
issuer: "kri-it"
|
|
access-token-validity-seconds: 86400
|
|
refresh-token-validity-seconds: 604800
|
|
apikey:
|
|
enabled: false
|
|
header-name: "X-API-Key"
|
|
allowed-paths: []
|
|
excluded-paths: []
|
|
service-code: "example-service"
|
|
preload-on-startup: false
|
|
admin-api-enabled: false
|
|
admin-allow-ips:
|
|
- "127.0.0.1/32"
|
|
- "localhost"
|
|
- "0:0:0:0:0:0:0:1"
|
|
db:
|
|
url: "jdbc:mysql://localhost:3306/kri_common?characterEncoding=UTF-8"
|
|
username: "app"
|
|
password: "secret"
|
|
driver-class-name: "com.mysql.cj.jdbc.Driver"
|
|
jpa:
|
|
show-sql: false
|
|
format-sql: false
|
|
crypto:
|
|
aes:
|
|
active-key-id: "key-2026"
|
|
keys:
|
|
key-2026: "replace-with-a-service-master-key"
|
|
algorithm: AES_256_GCM
|
|
tag-layout: APPENDED
|
|
kdf:
|
|
iterations: 600000
|
|
salt-length: 16
|
|
hash:
|
|
bcrypt:
|
|
strength: 12
|
|
security:
|
|
enabled: true
|
|
allowed-ips:
|
|
- "127.0.0.1"
|
|
- "10.0.0.0/8"
|
|
public-paths:
|
|
- "/v3/api-docs/**"
|
|
- "/swagger-ui.html"
|
|
- "/swagger-ui/**"
|
|
swagger:
|
|
enabled: true
|
|
title: "KRI API"
|
|
description: "KRI Common API Docs"
|
|
version: "v1"
|
|
base-package:
|
|
- "com.example.api"
|
|
allowed-ips:
|
|
- "127.0.0.1"
|
|
- "localhost"
|
|
web:
|
|
enabled: true
|
|
mdc:
|
|
enabled: true
|
|
redis:
|
|
enabled: false
|
|
scheduling:
|
|
enabled: false
|
|
error:
|
|
expose:
|
|
handler: false
|
|
service: false
|
|
```
|
|
|
|
운영 서비스에서는 JWT secret, API Key DB 접속 정보, Swagger/API Key admin 허용 IP를 반드시 서비스 환경에 맞게 override해야 합니다.
|
|
|
|
### `kri.crypto`
|
|
|
|
- `aes.active-key-id`: 직접 master key를 전달하지 않았을 때 사용할 key ID
|
|
- `aes.keys`: key ID별 master key. 복호화 호환을 위해 교체 전 key도 필요한 기간 동안 유지
|
|
- `aes.algorithm`: 기본값 `AES_256_GCM`
|
|
- `aes.tag-layout`: 기본값 `APPENDED`
|
|
- `aes.kdf.iterations`: PBKDF2 반복 횟수, 기본값 `600000`
|
|
- `aes.kdf.salt-length`: 자동 생성 salt 길이, 기본값 `16`
|
|
- `hash.bcrypt.strength`: 기본 BCrypt cost, 기본값 `12`, 허용 범위 `4..31`
|
|
|
|
`kri.crypto.enabled` 설정은 없습니다. Crypto API Bean은 항상 자동 구성되며, YML 키가 없어도
|
|
호출 시 master key를 직접 전달할 수 있습니다. 설정과 호출 양쪽에 키가 있으면 직접 전달한 키가
|
|
우선합니다. master key를 소스에 커밋하거나 로그와 예외에 출력하지 마십시오.
|
|
|
|
### `kri.auth.jwt`
|
|
|
|
관련 클래스:
|
|
|
|
- `JwtAutoConfiguration`
|
|
- `JwtProperties`
|
|
- `JwtService`
|
|
|
|
기능:
|
|
|
|
- `JwtProperties`를 바탕으로 `JwtService` Bean 등록
|
|
- access token, refresh token 유효 시간 설정
|
|
- issuer, HMAC secret 설정
|
|
|
|
기본값은 개발 편의를 위한 값이므로 운영에서는 `secret`을 반드시 교체해야 합니다.
|
|
|
|
### `kri.auth.apikey`
|
|
|
|
관련 클래스:
|
|
|
|
- `ApiKeyProperties`
|
|
- `ApiKeyJpaAutoConfiguration`
|
|
- `ApiKeyPreloadAutoConfiguration`
|
|
- `ApiKeyAdminAutoConfiguration`
|
|
- `ApiKeyAuthFilter`
|
|
- `PreloadedApiKeyUserClaimsProvider`
|
|
|
|
기능:
|
|
|
|
- `enabled=true`일 때 API Key 인증 기능 활성화
|
|
- `header-name`으로 API Key를 읽을 HTTP header 지정
|
|
- `allowed-paths`가 한 개 이상이면 일치하는 요청에서만 API Key 인증 시도
|
|
- `excluded-paths`와 일치하는 요청은 허용 여부와 관계없이 API Key 인증에서 제외
|
|
- JPA repository를 통해 서비스별 활성 API Key를 preload cache로 적재
|
|
- `ApiKeyAuthFilter`가 API Key를 `Authentication`으로 변환
|
|
- `admin-api-enabled=true`일 때 내부 reload/cache endpoint 노출
|
|
|
|
API Key를 일부 API에서만 인증 수단으로 허용하려면 다음처럼 설정합니다.
|
|
|
|
```yaml
|
|
kri:
|
|
auth:
|
|
apikey:
|
|
enabled: true
|
|
header-name: X-API-Key
|
|
service-code: kric-contact-service
|
|
allowed-paths:
|
|
- /api/v1/list/update/**
|
|
- /api/v1/external/**
|
|
excluded-paths:
|
|
- /api/v1/external/admin/**
|
|
```
|
|
|
|
경로 설정의 동작은 다음과 같습니다. 두 설정이 겹치면 `excluded-paths`가 우선합니다.
|
|
|
|
| `allowed-paths` | `excluded-paths` | API Key 인증 대상 |
|
|
|---|---|---|
|
|
| 비어 있음 | 비어 있음 | 기존처럼 모든 요청 |
|
|
| 비어 있음 | 설정됨 | 제외 패턴과 일치하지 않는 요청 |
|
|
| 설정됨 | 비어 있음 | 허용 패턴과 일치하는 요청 |
|
|
| 설정됨 | 설정됨 | 허용 패턴과 일치하면서 제외 패턴과 일치하지 않는 요청 |
|
|
|
|
하위 호환 규칙과 매칭 방식은 다음과 같습니다.
|
|
|
|
- 각 속성의 미설정, `null`, 빈 목록 또는 공백 패턴만 있는 목록은 해당 경로 제한을 적용하지 않습니다.
|
|
- `allowed-paths`에 유효한 패턴이 하나 이상이면 그중 하나와 일치하는 요청만 인증 대상이 됩니다.
|
|
- `excluded-paths`에 유효한 패턴이 하나 이상이면 그중 하나와 일치하는 요청은 항상 인증 대상에서 제외됩니다.
|
|
- Spring 경로 패턴을 사용하며 `*`는 한 경로 구간, `**`는 하위 경로 전체와 매칭합니다.
|
|
- HTTP method는 구분하지 않고, context path와 query string은 매칭 대상에서 제외합니다.
|
|
- 패턴은 `/`로 시작해야 하며 잘못된 패턴은 애플리케이션 기동 시 오류로 처리됩니다.
|
|
- 두 설정은 API Key 인증 필터의 적용 범위만 제한합니다. 경로를 공개하거나 접근 권한을 직접 부여하지 않습니다.
|
|
- 공개 경로는 별도 설정인 `kri.security.public-paths`로 관리합니다.
|
|
|
|
주의:
|
|
|
|
- DB preload 방식은 JPA와 DataSource 관련 classpath가 필요합니다.
|
|
- JPA classpath가 없으면 DB preload 자동 구성만 건너뛰며, 서비스가 직접 등록한 `ApiKeyUserClaimsProvider`는 사용할 수 있습니다.
|
|
- `service-code`가 비어 있으면 preload cache는 비어 있게 됩니다.
|
|
- admin API는 IP allowlist를 통과해야 합니다.
|
|
|
|
### `kri.security`
|
|
|
|
`allowed-ips` is optional. When it is empty, the default security chain behaves as before.
|
|
When it has values, `public-paths` require an allowed client IP but no authentication, and all
|
|
other paths require both an allowed client IP and authentication. Exact IPs, CIDR values, and
|
|
`localhost` are supported.
|
|
|
|
관련 클래스:
|
|
|
|
- `KriSecurityAutoConfiguration`
|
|
- `KriSecurityProperties`
|
|
- `JwtAuthenticationFilter`
|
|
- `ApiKeyAuthFilter`
|
|
|
|
기능:
|
|
|
|
- 기본 Spring Security filter chain 등록
|
|
- HTTP Basic, CSRF 비활성화
|
|
- CORS 기본 활성화
|
|
- stateless session policy 적용
|
|
- `public-paths`는 `permitAll`
|
|
- 나머지 요청은 인증 필요
|
|
- API Key filter가 있으면 먼저 적용하고, 그 다음 JWT filter 적용
|
|
- `@EnableMethodSecurity(jsr250Enabled=true, prePostEnabled=true)` 활성화
|
|
|
|
서비스가 자체 `SecurityFilterChain` Bean을 등록하면 이 라이브러리의 기본 filter chain은 생성되지 않습니다.
|
|
|
|
### `kri.swagger`
|
|
|
|
관련 클래스:
|
|
|
|
- `KriSwaggerAutoConfiguration`
|
|
- `KriSwaggerProperties`
|
|
- `SwaggerIpFilter`
|
|
- `CodeEnumModelConverter`
|
|
- `CodeEnumOpenApiCustomizer`
|
|
|
|
기능:
|
|
|
|
- OpenAPI metadata 설정
|
|
- Bearer JWT와 API Key security scheme 등록
|
|
- `GroupedOpenApi` group `kri-api` 생성
|
|
- `/api/**`, `/internal/**` 경로 문서화
|
|
- `base-package`가 있으면 해당 패키지만 scan
|
|
- API Key admin API가 활성화되면 내부 admin endpoint package도 scan
|
|
- Swagger UI/API docs 접근 IP 제한
|
|
- `CodeEnum` 구현 enum의 schema/parameter 설명 보강
|
|
- 서버가 주입하는 `RequestUserContext`를 요청 입력 문서에서 제외
|
|
|
|
### `kri.web`
|
|
|
|
관련 클래스:
|
|
|
|
- `CommonWebAutoConfiguration`
|
|
- `ErrorAdvice`
|
|
- `ExternalApiErrorAutoConfiguration`
|
|
- `ExternalApiResponseAdvice`
|
|
- `TraceFilter`
|
|
- `ServiceMdcAspect`
|
|
- `RequestUserContextArgumentResolver`
|
|
- `CodeEnumConverter`
|
|
|
|
기능:
|
|
|
|
- 공통 예외 응답 처리
|
|
- 요청별 trace filter 등록
|
|
- handler/service 정보를 MDC에 기록
|
|
- `RequestUserContext` 컨트롤러 argument resolver 등록
|
|
- 전체 CORS mapping 등록
|
|
- `CodeEnum` converter 등록
|
|
|
|
`kri.web.enabled` 기본값은 `true`, `kri.web.mdc.enabled` 기본값은 `true`입니다.
|
|
|
|
### `kri.redis`
|
|
|
|
관련 클래스:
|
|
|
|
- `CommonRedisAutoConfiguration`
|
|
- `RedisQueueHelper`
|
|
|
|
`kri.redis.enabled=true`, `RedisTemplate` classpath, `RedisConnectionFactory` Bean이 모두 있을 때 `RedisQueueHelper`를 등록합니다. 기본값은 `false`입니다.
|
|
|
|
### `kri.scheduling`
|
|
|
|
관련 클래스:
|
|
|
|
- `CommonSchedulingAutoConfiguration`
|
|
|
|
`kri.scheduling.enabled=true`일 때 Spring scheduling을 활성화합니다. 기본값은 `false`입니다.
|
|
|
|
### `kri.error.expose.*`
|
|
|
|
관련 클래스:
|
|
|
|
- `ErrorAdvice`
|
|
|
|
공통 에러 응답에 handler/service MDC 정보를 포함할지 제어합니다.
|
|
|
|
- `kri.error.expose.handler`
|
|
- `kri.error.expose.service`
|
|
|
|
---
|
|
|
|
## 자동 노출 endpoint
|
|
|
|
### API Key admin
|
|
|
|
클래스:
|
|
|
|
- `com.kri.common.endpoint.auth.apikey.ApiKeyAdminController`
|
|
|
|
노출 조건:
|
|
|
|
- `kri.auth.apikey.enabled=true`
|
|
- `kri.auth.apikey.admin-api-enabled=true`
|
|
- `PreloadedApiKeyUserClaimsProvider` Bean 존재
|
|
|
|
Endpoint:
|
|
|
|
- `POST /internal/apikey/reload`: DB에서 API Key cache 재적재
|
|
- `GET /internal/apikey/cache`: 현재 메모리 cache 조회, API Key는 mask 처리
|
|
|
|
접근 제어:
|
|
|
|
- `kri.auth.apikey.admin-allow-ips`
|
|
- 기본 허용값은 local address 계열
|
|
- 허용되지 않은 IP는 `403`
|
|
- admin API가 비활성화된 상태에서는 `404`
|
|
|
|
---
|
|
|
|
## 자동 구성 목록
|
|
|
|
자동 구성 목록은 `src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`에 선언되어 있습니다.
|
|
|
|
- `com.kri.common.autoconfigure.auth.jwt.JwtAutoConfiguration`
|
|
- `com.kri.common.autoconfigure.auth.apikey.ApiKeyJpaAutoConfiguration`
|
|
- `com.kri.common.autoconfigure.auth.apikey.ApiKeyPreloadAutoConfiguration`
|
|
- `com.kri.common.autoconfigure.auth.apikey.ApiKeyAdminAutoConfiguration`
|
|
- `com.kri.common.autoconfigure.security.KriSecurityAutoConfiguration`
|
|
- `com.kri.common.autoconfigure.web.CommonWebAutoConfiguration`
|
|
- `com.kri.common.autoconfigure.swagger.KriSwaggerAutoConfiguration`
|
|
- `com.kri.common.autoconfigure.redis.CommonRedisAutoConfiguration`
|
|
- `com.kri.common.autoconfigure.scheduling.CommonSchedulingAutoConfiguration`
|
|
- `com.kri.common.autoconfigure.crypto.CryptoAutoConfiguration`
|
|
|
|
---
|
|
|
|
## 사용 시 권장 기준
|
|
|
|
- 서비스 코드에서는 가능한 한 `feature` 패키지의 타입만 직접 사용합니다.
|
|
- `runtime` 패키지는 자동 구성으로 조립되는 내부 구현으로 보고 직접 의존을 피합니다.
|
|
- 운영 환경에서는 기본 JWT secret과 API Key DB 설정을 사용하지 않습니다.
|
|
- AES 신규 데이터는 GCM을 사용하고, MD5·SHA-1·AES-CBC는 레거시 호환 범위로 제한합니다.
|
|
- 자체 보안 정책이 필요한 서비스는 직접 `SecurityFilterChain` Bean을 등록해 기본 구성을 대체합니다.
|
|
- Swagger 접근 제한은 운영망/관리망 정책에 맞춰 `allowed-ips`를 명시합니다.
|
|
- 대용량 Excel은 일반 `Workbook` 변환보다 streaming API를 우선 검토합니다.
|
|
- 배포 전 `./gradlew compileJava`로 컴파일을 확인합니다.
|
|
|
|
---
|
|
|
|
## 변경 이력
|
|
|
|
- 2026-08-06: `beta.1.6.3`에서 non-ASCII multipart 파일명을 ASCII fallback/
|
|
`filename*` 없이 원본 `filename`의 UTF-8 바이트로 전송하도록 복원했습니다.
|
|
- 2026-08-06: `beta.1.6.2`에서 non-ASCII multipart 파일명에 ASCII `filename`
|
|
fallback과 UTF-8 `filename*`를 추가했습니다.
|
|
- 2026-08-04: `kri.auth.apikey.allowed-paths`와 `kri.auth.apikey.excluded-paths`를 추가했습니다. 미설정·`null`·빈 목록은 기존 전역 API Key 인증 동작을 유지하며, 제외 패턴은 허용 패턴보다 우선합니다.
|