260701_01_ENH: IP 화이트 리스트 기능 추가 없으면 모든 IP허용
This commit is contained in:
230
Agents.md
Normal file
230
Agents.md
Normal file
@@ -0,0 +1,230 @@
|
||||
# Agents.md
|
||||
|
||||
This file is for AI agents modifying or consuming this repository. Keep it concise, factual, and synchronized with source code.
|
||||
|
||||
## Repository Identity
|
||||
|
||||
- Project: `KriCommon`
|
||||
- Type: Java 17 Spring Boot starter/library
|
||||
- Build: Gradle `java-library` + `maven-publish`
|
||||
- Maven coordinates: `com.kri.common:starter:<commonVer>`
|
||||
- Version source: `build.gradle` variable `commonVer`
|
||||
- Main source root: `src/main/java`
|
||||
- Auto-configuration registration: `src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`
|
||||
|
||||
## Package Contract
|
||||
|
||||
- `com.kri.common.autoconfigure`: Spring Boot auto-configurations and configuration property classes.
|
||||
- `com.kri.common.feature`: Public API intended for service code to import directly.
|
||||
- `com.kri.common.runtime`: Runtime implementation assembled by auto-configuration. Treat as internal unless there is no public feature API.
|
||||
- `com.kri.common.endpoint`: Optional common controllers exposed by configuration.
|
||||
|
||||
When adding features, prefer exposing stable service-facing types under `feature` and wiring implementation under `autoconfigure`/`runtime`.
|
||||
|
||||
## Build Commands
|
||||
|
||||
```bash
|
||||
./gradlew compileJava
|
||||
./gradlew publishReleasePublicationToGiteaRepository
|
||||
```
|
||||
|
||||
On Windows PowerShell, use:
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat compileJava
|
||||
.\gradlew.bat publishReleasePublicationToGiteaRepository
|
||||
```
|
||||
|
||||
Publishing requires `giteaUser`/`giteaToken` Gradle properties or `GITEA_USER`/`GITEA_TOKEN` environment variables. The publish task depends on `checkGiteaPackageVersionNotExists`.
|
||||
|
||||
## Dependency Model
|
||||
|
||||
The library intentionally uses many `compileOnly` Spring dependencies. Do not assume a class is present at runtime unless the consuming service has the matching starter.
|
||||
|
||||
Important dependency categories:
|
||||
|
||||
- Spring Boot BOM: `org.springframework.boot:spring-boot-dependencies:3.5.7`
|
||||
- Java: 17
|
||||
- JWT: JJWT `0.12.6`
|
||||
- JSON: Jackson Databind `2.17.0`
|
||||
- Excel: Apache POI `5.5.1`
|
||||
- Spring Web/Security/JPA/Redis/AOP/Swagger dependencies are mostly `compileOnly`
|
||||
|
||||
When adding auto-configuration, use `@ConditionalOnClass`, `@ConditionalOnBean`, `@ConditionalOnMissingBean`, and property conditions to avoid breaking consumers that do not include optional starters.
|
||||
|
||||
## Configuration Prefixes
|
||||
|
||||
Only use `kri.*` prefixes.
|
||||
|
||||
Known prefixes:
|
||||
|
||||
- `kri.auth.jwt`
|
||||
- `kri.auth.apikey`
|
||||
- `kri.security`
|
||||
- `kri.swagger`
|
||||
- `kri.web`
|
||||
- `kri.web.mdc`
|
||||
- `kri.redis`
|
||||
- `kri.scheduling`
|
||||
- `kri.error.expose`
|
||||
|
||||
## Auto-Configurations
|
||||
|
||||
Declared 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`
|
||||
|
||||
If a new auto-configuration must be active for consumers, add it to `AutoConfiguration.imports`.
|
||||
|
||||
## Feature Map
|
||||
|
||||
### JWT
|
||||
|
||||
- Public classes: `JwtService`, `JwtUserClaimsDto`
|
||||
- Config: `kri.auth.jwt`
|
||||
- Auto-config: `JwtAutoConfiguration`
|
||||
- Main operations: generate access/refresh tokens, parse token, convert claims to `JwtUserClaimsDto`, convert token/DTO to Spring Security `Authentication`
|
||||
- Claims DTO fields: `userId`, `userCmpn`, `userTeam`, `userName`, `userRole`
|
||||
|
||||
Security note: default secrets in source are not production-safe. Documentation and examples should instruct consumers to override secrets.
|
||||
|
||||
### API Key Authentication
|
||||
|
||||
- Public extension point: `ApiKeyUserClaimsProvider`
|
||||
- Runtime filter: `ApiKeyAuthFilter`
|
||||
- Runtime preload provider: `PreloadedApiKeyUserClaimsProvider`
|
||||
- Config: `kri.auth.apikey`
|
||||
- Optional endpoint: `ApiKeyAdminController`
|
||||
- Admin endpoints:
|
||||
- `POST /internal/apikey/reload`
|
||||
- `GET /internal/apikey/cache`
|
||||
|
||||
Behavior:
|
||||
|
||||
- API key is read from `kri.auth.apikey.header-name`, default `X-API-Key`.
|
||||
- If authentication already exists in `SecurityContextHolder`, API key filter does nothing.
|
||||
- If provider resolves a key, the result is converted to `Authentication` using `JwtService.toAuthentication`.
|
||||
- Preloaded provider returns empty cache when `service-code` is blank.
|
||||
- Admin endpoint is exposed only when `admin-api-enabled=true` and the preload provider exists.
|
||||
- Admin endpoint has IP allowlist enforcement.
|
||||
|
||||
### Security
|
||||
|
||||
- Auto-config: `KriSecurityAutoConfiguration`
|
||||
- Config: `kri.security`
|
||||
- Default enabled: `true`
|
||||
- Registers `JwtAuthenticationFilter` and default `SecurityFilterChain` only when consumer has no `SecurityFilterChain` bean.
|
||||
- Filter order inside the default chain: optional `ApiKeyAuthFilter`, then `JwtAuthenticationFilter`, both before `UsernamePasswordAuthenticationFilter`.
|
||||
- Default chain disables HTTP Basic and CSRF, uses stateless sessions, optionally enforces `allowed-ips`, permits `public-paths`, authenticates all other requests.
|
||||
- When `kri.security.allowed-ips` is non-empty, `public-paths` require an allowed client IP but no authentication; all other paths require both allowed IP and authentication.
|
||||
- Method security is enabled with JSR-250 and pre/post annotations.
|
||||
|
||||
### Web
|
||||
|
||||
- Auto-config: `CommonWebAutoConfiguration`
|
||||
- Config: `kri.web.enabled`, default `true`
|
||||
- MDC config: `kri.web.mdc.enabled`, default `true`
|
||||
- Registers:
|
||||
- `ErrorAdvice`
|
||||
- `TraceFilter`
|
||||
- `ServiceMdcAspect` when AspectJ is present and MDC is enabled
|
||||
- MVC interceptor for handler MDC when MDC is enabled
|
||||
- `RequestUserContextArgumentResolver` when `JwtService` bean exists
|
||||
- `CodeEnumConverter`
|
||||
- global CORS mapping
|
||||
|
||||
### Swagger/OpenAPI
|
||||
|
||||
- Auto-config: `KriSwaggerAutoConfiguration`
|
||||
- Config: `kri.swagger`
|
||||
- Default enabled: `true`
|
||||
- Requires OpenAPI/springdoc classes on classpath.
|
||||
- Defines security schemes `BearerAuth` and `ApiKeyAuth`.
|
||||
- Creates `GroupedOpenApi` named `kriGroupedOpenApi`, group `kri-api`, paths `/api/**` and `/internal/**`.
|
||||
- Uses `kri.swagger.base-package` for package scanning.
|
||||
- Adds API key admin package when `kri.auth.apikey.admin-api-enabled=true`.
|
||||
- Registers `SwaggerIpFilter` for `/swagger-ui/*`, `/v3/api-docs/*`, `/swagger-ui.html`.
|
||||
- Adds CodeEnum model/property/parameter OpenAPI support.
|
||||
|
||||
### Redis
|
||||
|
||||
- Auto-config: `CommonRedisAutoConfiguration`
|
||||
- Config: `kri.redis.enabled`
|
||||
- Default enabled: `false`
|
||||
- Requires `RedisTemplate` class and `RedisConnectionFactory` bean.
|
||||
- Registers `RedisQueueHelper`.
|
||||
|
||||
### Scheduling
|
||||
|
||||
- Auto-config: `CommonSchedulingAutoConfiguration`
|
||||
- Config: `kri.scheduling.enabled`
|
||||
- Default enabled: `false`
|
||||
- Enables Spring scheduling.
|
||||
|
||||
### Excel
|
||||
|
||||
- Public classes: `ExcelMapper`, `ExcelUtil`, `ExcelColumn`, `StreamingReadOptions`
|
||||
- Supports DTO workbook read/write, map workbook read/write, SXSSF streaming write, SAX streaming read.
|
||||
- `ExcelColumn` fields: `header`, `order`, `width`.
|
||||
- `StreamingReadOptions.DEFAULT`: sheet index `0`, header row index `1`, identity header normalizer.
|
||||
|
||||
### JSON
|
||||
|
||||
- Public class: `JsonUtil`
|
||||
- All methods require an explicit `ObjectMapper`.
|
||||
- Do not introduce hidden global ObjectMapper state without a deliberate API decision.
|
||||
|
||||
### Date/Time
|
||||
|
||||
- Public classes: `DateTimeUtil`, `LenientLocalDateTime`, `LenientLocalDateTimeDeserializer`
|
||||
- KST zone constant: `Asia/Seoul`
|
||||
- UTC constant: `ZoneOffset.UTC`
|
||||
|
||||
### Enum
|
||||
|
||||
- Public classes: `CodeEnum`, `CodeEnumUtils`
|
||||
- Runtime MVC converter: `CodeEnumConverter`
|
||||
- JPA base converter: `AbstractCodeEnumConverter`
|
||||
- Swagger metadata support exists in `runtime.swagger`.
|
||||
|
||||
### JPA
|
||||
|
||||
- Public classes: `BaseUuidEntity`, `AbstractCodeEnumConverter`, `EntityColumnAccessor`
|
||||
- API key JPA runtime entities/repository are internal to `runtime.auth.apikey.persistence`.
|
||||
|
||||
### Utilities
|
||||
|
||||
- `FileUtil`: filename sanitizing, extension extraction, path-like filename extraction
|
||||
- `StringUtil`: null/blank checks, normalization, basic validation, escaping
|
||||
- `NumericUtil`: numeric checks and safe parsing
|
||||
- `CollectionUtil`: empty checks
|
||||
- `CommonUtil`: UUID helpers
|
||||
|
||||
## Coding Rules For Agents
|
||||
|
||||
- Do not move public APIs out of `feature` without a compatibility plan.
|
||||
- Do not make optional Spring integrations unconditional.
|
||||
- Do not add new configuration prefixes outside `kri.*`.
|
||||
- Do not hard-code service-specific secrets or credentials in new code or docs.
|
||||
- Do not directly expose raw API keys in endpoints or logs.
|
||||
- Prefer `@ConditionalOnMissingBean` for beans consumers may override.
|
||||
- Prefer explicit examples in README that use placeholder secrets and local URLs.
|
||||
- Keep README human-readable and keep this file agent-readable.
|
||||
- If changing behavior, update README and this file in the same change.
|
||||
- Run `.\gradlew.bat compileJava` before finalizing when possible.
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
- `.\gradlew.bat compileJava`
|
||||
- Confirm any new auto-config is listed in `AutoConfiguration.imports`.
|
||||
- Confirm property names in docs match `@ConfigurationProperties` fields.
|
||||
- Confirm optional integrations have classpath/bean/property conditions.
|
||||
- Confirm public examples import from `com.kri.common.feature.*` unless intentionally documenting internals.
|
||||
606
README.md
606
README.md
@@ -1,149 +1,339 @@
|
||||
# KriCommon 설정/기능 정리
|
||||
|
||||
## 개요
|
||||
KriCommon은 KRI 계열 Spring Boot 서비스에서 반복해서 쓰는 인증, 보안, 웹, Swagger, Redis, Excel, JSON, 날짜/시간, JPA 보조 기능을 모은 Java 17 라이브러리입니다.
|
||||
|
||||
현재 패키지 구조는 아래 4축으로 정리되어 있습니다.
|
||||
라이브러리의 패키지는 역할에 따라 다음 4개 축으로 나뉩니다.
|
||||
|
||||
- `com.kri.common.autoconfigure`: Spring Boot 자동 구성 진입점과 `Properties`
|
||||
- `com.kri.common.feature`: 서비스에서 직접 import/주입/구현하는 공개 기능
|
||||
- `com.kri.common.runtime`: 자동 구성에 의해 조립되어 동작하는 내부 실행 구성요소
|
||||
- `com.kri.common.endpoint`: yml 설정으로 자동 노출되는 공통 엔드포인트
|
||||
- `com.kri.common.autoconfigure`: Spring Boot 자동 구성과 `@ConfigurationProperties`
|
||||
- `com.kri.common.feature`: 서비스 코드가 직접 import해서 쓰는 공개 기능
|
||||
- `com.kri.common.runtime`: 자동 구성으로 조립되는 필터, 컨버터, 어드바이스 등 내부 실행 요소
|
||||
- `com.kri.common.endpoint`: 설정에 따라 노출되는 공통 관리 API
|
||||
|
||||
설정 키는 `kri.*`만 사용합니다.
|
||||
설정 prefix는 `kri.*`만 사용합니다.
|
||||
|
||||
---
|
||||
|
||||
## 직접 import해서 사용하는 기능
|
||||
## 빌드와 배포
|
||||
|
||||
### 인증/보안
|
||||
- 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
|
||||
|
||||
#### `com.kri.common.feature.auth.jwt.JwtService`
|
||||
```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;
|
||||
```
|
||||
|
||||
- 사용법: 빈 주입 후 `generateAccessToken`, `generateRefreshToken`, `toAuthentication` 호출
|
||||
- 설명: JWT 발급, 파싱, `Authentication` 변환을 처리합니다.
|
||||
JWT 발급, 파싱, claims 변환, Spring Security `Authentication` 변환을 담당합니다.
|
||||
|
||||
#### `com.kri.common.feature.auth.dto.JwtUserClaimsDto`
|
||||
주요 메서드:
|
||||
|
||||
```java
|
||||
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
|
||||
```
|
||||
- `generateAccessToken(JwtUserClaimsDto userClaims)`
|
||||
- `generateRefreshToken(String userId)`
|
||||
- `parseToken(String token)`
|
||||
- `getClaims(String token)`
|
||||
- `toUserClaimsDto(Claims claims)`
|
||||
- `toUserClaimsDto(String token)`
|
||||
- `toAuthentication(JwtUserClaimsDto dto)`
|
||||
- `toAuthentication(String token)`
|
||||
|
||||
- 사용법: builder로 사용자 정보를 생성해 `JwtService`에 전달
|
||||
- 설명: JWT 클레임 공통 DTO입니다.
|
||||
`JwtUserClaimsDto`에 포함되는 필드는 `userId`, `userCmpn`, `userTeam`, `userName`, `userRole`입니다.
|
||||
|
||||
#### `com.kri.common.feature.auth.apikey.ApiKeyUserClaimsProvider`
|
||||
#### `ApiKeyUserClaimsProvider`
|
||||
|
||||
```java
|
||||
import com.kri.common.feature.auth.apikey.ApiKeyUserClaimsProvider;
|
||||
```
|
||||
|
||||
- 사용법: 서비스에서 구현체를 만들어 Bean 등록
|
||||
- 설명: API Key를 사용자 클레임으로 매핑하는 공개 확장 포인트입니다.
|
||||
API Key를 `JwtUserClaimsDto`로 매핑하는 확장 인터페이스입니다.
|
||||
|
||||
#### `com.kri.common.feature.web.RequestUserContext`
|
||||
```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;
|
||||
```
|
||||
|
||||
- 사용법: 컨트롤러 파라미터로 선언
|
||||
- 설명: 현재 인증 사용자와 클라이언트 IP를 전달받는 요청 컨텍스트입니다.
|
||||
|
||||
### 웹/페이징
|
||||
|
||||
#### `com.kri.common.feature.web.page.PageRequestDto`
|
||||
컨트롤러 파라미터로 선언하면 현재 인증 사용자와 client IP를 받을 수 있습니다. `JwtService` Bean이 있을 때 `RequestUserContextArgumentResolver`가 자동 등록됩니다.
|
||||
|
||||
```java
|
||||
import com.kri.common.feature.web.page.PageRequestDto;
|
||||
@GetMapping("/me")
|
||||
public Object me(RequestUserContext user) {
|
||||
return user;
|
||||
}
|
||||
```
|
||||
|
||||
- 사용법: 조회 API 요청 DTO로 사용
|
||||
- 설명: pageIndex, pageSize, sortBy, sortDir를 공통 형식으로 받습니다.
|
||||
필드는 `userId`, `userCmpn`, `userTeam`, `userName`, `userRole`, `clientIp`이며, `isAuthenticated()`는 `userId != null`일 때 `true`를 반환합니다.
|
||||
|
||||
#### `com.kri.common.feature.web.page.Pageables`
|
||||
### 예외/페이징
|
||||
|
||||
#### `BusinessException`
|
||||
|
||||
서비스 레이어에서 HTTP 상태, 에러 코드, 메시지, 부가 정보를 함께 담아 던지는 런타임 예외입니다.
|
||||
|
||||
```java
|
||||
import com.kri.common.feature.web.page.Pageables;
|
||||
throw BusinessException.badRequest("INVALID_INPUT", "입력값이 올바르지 않습니다.");
|
||||
```
|
||||
|
||||
- 사용법: `Pageables.of(req, EntityOrDto.class)`
|
||||
- 설명: 정렬 가능 필드를 검증해 `Pageable` 객체를 만듭니다.
|
||||
팩토리 메서드:
|
||||
|
||||
#### `com.kri.common.feature.web.page.PageResponseDto`
|
||||
- `badRequest`
|
||||
- `unauthorized`
|
||||
- `forbidden`
|
||||
- `notFound`
|
||||
- `conflict`
|
||||
- `validationError`
|
||||
- `internalError`
|
||||
- `of`
|
||||
|
||||
`with(String key, Object value)`로 응답에 포함할 부가 정보를 추가할 수 있습니다.
|
||||
|
||||
#### `PageRequestDto`, `Pageables`, `PageResponseDto`
|
||||
|
||||
```java
|
||||
import com.kri.common.feature.web.page.PageResponseDto;
|
||||
Pageable pageable = Pageables.of(req, ProjectEntity.class);
|
||||
PageResponseDto<ProjectDto> response = PageResponseDto.from(page);
|
||||
```
|
||||
|
||||
- 사용법: `PageResponseDto.from(page)`
|
||||
- 설명: Spring Data `Page`를 API 응답용 DTO로 감쌉니다.
|
||||
`PageRequestDto` 기본값:
|
||||
|
||||
- `pageIndex = 0`
|
||||
- `pageSize = 10`
|
||||
- `sortBy = "prjctIdx"`
|
||||
- `sortDir = "desc"`
|
||||
|
||||
`Pageables.of`는 정렬 필드가 대상 클래스에 존재하는지 검증한 뒤 `Pageable`을 생성합니다.
|
||||
|
||||
### Redis
|
||||
|
||||
#### `com.kri.common.feature.redis.RedisQueueHelper`
|
||||
#### `RedisQueueHelper`
|
||||
|
||||
```java
|
||||
import com.kri.common.feature.redis.RedisQueueHelper;
|
||||
```
|
||||
|
||||
- 사용법: 자동 구성 빈 주입 후 `enqueue`, `blockingDequeue` 사용
|
||||
- 설명: Redis List 기반 큐 처리 헬퍼입니다.
|
||||
`StringRedisTemplate` 기반 Redis List 큐 helper입니다.
|
||||
|
||||
### HTTP/JSON/Excel
|
||||
- `enqueue(String key, String value)`
|
||||
- `blockingDequeue(String key, Duration timeout)`
|
||||
|
||||
#### `com.kri.common.feature.http.ExternalApiClient`
|
||||
`kri.redis.enabled=true`이고 `RedisConnectionFactory`가 있으면 자동 등록됩니다.
|
||||
|
||||
### HTTP
|
||||
|
||||
#### `ExternalApiClient`, `ExternalApiResponse`
|
||||
|
||||
JDK `HttpClient` 기반 경량 HTTP client입니다.
|
||||
|
||||
```java
|
||||
import com.kri.common.feature.http.ExternalApiClient;
|
||||
ExternalApiClient client = new ExternalApiClient();
|
||||
ExternalApiResponse res = client.post(url, headers, jsonBody);
|
||||
```
|
||||
|
||||
- 사용법: `new ExternalApiClient()` 또는 커스텀 `HttpClient`로 생성
|
||||
- 설명: 문자열 body 기반의 경량 HTTP 클라이언트입니다.
|
||||
지원 메서드:
|
||||
|
||||
#### `com.kri.common.feature.http.ExternalApiResponse`
|
||||
- `get`
|
||||
- `delete`
|
||||
- `post`
|
||||
- `put`
|
||||
- `patch`
|
||||
|
||||
응답은 `statusCode`, `headers`, `body`를 제공합니다.
|
||||
|
||||
### JSON
|
||||
|
||||
#### `JsonUtil`
|
||||
|
||||
Jackson `ObjectMapper`를 명시적으로 받아 JSON 변환을 수행하는 static helper입니다.
|
||||
|
||||
- `toMap`
|
||||
- `parseJsonToMap`
|
||||
- `toJson`
|
||||
- `toPrettyJson`
|
||||
- `fromJson`
|
||||
- `deepCopy`
|
||||
- `convert`
|
||||
|
||||
### Excel
|
||||
|
||||
#### `ExcelColumn`
|
||||
|
||||
DTO 필드와 Excel 컬럼을 매핑하는 애너테이션입니다.
|
||||
|
||||
```java
|
||||
import com.kri.common.feature.http.ExternalApiResponse;
|
||||
@ExcelColumn(header = "사용자 ID", order = 1, width = 20)
|
||||
private String userId;
|
||||
```
|
||||
|
||||
- 사용법: `ExternalApiClient` 응답 객체로 사용
|
||||
- 설명: statusCode, headers, body를 묶어 반환합니다.
|
||||
- `header`: Excel 헤더명
|
||||
- `order`: 컬럼 순서
|
||||
- `width`: 문자 폭 기준 너비, `-1`이면 기본 auto size 흐름 사용
|
||||
|
||||
#### `com.kri.common.feature.json.JsonUtil`
|
||||
#### `ExcelMapper`
|
||||
|
||||
Apache POI 기반 Excel 읽기/쓰기 helper입니다.
|
||||
|
||||
주요 기능:
|
||||
|
||||
- DTO 리스트를 `Workbook`으로 쓰기
|
||||
- `Workbook`을 DTO 리스트로 읽기
|
||||
- `Map<String, ?>` 리스트를 Excel로 쓰기
|
||||
- Excel을 `List<Map<String, String>>`으로 읽기
|
||||
- `SXSSFWorkbook` 기반 대용량 스트리밍 쓰기
|
||||
- SAX 기반 대용량 스트리밍 읽기
|
||||
- streaming writer를 열어 row를 점진적으로 append
|
||||
|
||||
#### `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
|
||||
import com.kri.common.feature.json.JsonUtil;
|
||||
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");
|
||||
```
|
||||
|
||||
- 사용법: JSON 직렬화/역직렬화/맵 변환 수행
|
||||
- 설명: Jackson 보조 유틸입니다.
|
||||
웹 자동 구성은 request parameter/path variable의 문자열 값을 `CodeEnum` 구현 enum으로 변환하는 `CodeEnumConverter`를 등록합니다. Swagger 자동 구성은 `CodeEnum` schema/parameter 설명도 보강합니다.
|
||||
|
||||
#### `com.kri.common.feature.excel.ExcelMapper`
|
||||
### JPA
|
||||
|
||||
```java
|
||||
import com.kri.common.feature.excel.ExcelMapper;
|
||||
```
|
||||
#### `AbstractCodeEnumConverter`
|
||||
|
||||
- 사용법: DTO 리스트나 Map 리스트를 엑셀로 변환
|
||||
- 설명: 일반 처리와 대용량 스트리밍 읽기/쓰기를 지원합니다.
|
||||
JPA `AttributeConverter` 구현을 쉽게 만들기 위한 추상 클래스입니다.
|
||||
|
||||
### 날짜/시간/JPA/Enum/유틸
|
||||
#### `BaseUuidEntity`
|
||||
|
||||
- `com.kri.common.feature.datetime.*`: 날짜/시간 처리 유틸과 Jackson 어노테이션
|
||||
- `com.kri.common.feature.jpa.*`: JPA 베이스 엔티티와 enum converter
|
||||
- `com.kri.common.feature.enums.*`: 코드값 기반 enum 인터페이스와 유틸
|
||||
- `com.kri.common.feature.cache.*`: 리스트/맵 캐시 베이스 클래스
|
||||
- `com.kri.common.feature.file.FileUtil`: 파일명/확장자 유틸
|
||||
- `com.kri.common.feature.util.*`: 문자열, 숫자, UUID 보조 유틸
|
||||
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로 설정하는 기능
|
||||
## yml로 설정하는 자동 구성
|
||||
|
||||
### 전체 예시
|
||||
|
||||
@@ -151,173 +341,235 @@ import com.kri.common.feature.excel.ExcelMapper;
|
||||
kri:
|
||||
auth:
|
||||
jwt:
|
||||
# JWT 서명용 시크릿. 32바이트 이상 권장
|
||||
secret: "32byte-over-secret-value-required"
|
||||
# 토큰 발급자 식별자
|
||||
secret: "replace-with-service-secret-at-least-32-bytes"
|
||||
issuer: "kri-it"
|
||||
# Access Token 만료 시간(초)
|
||||
access-token-validity-seconds: 86400
|
||||
# Refresh Token 만료 시간(초)
|
||||
refresh-token-validity-seconds: 604800
|
||||
apikey:
|
||||
# API Key 인증 기능 활성화
|
||||
enabled: true
|
||||
# API Key를 읽을 HTTP 헤더명
|
||||
enabled: false
|
||||
header-name: "X-API-Key"
|
||||
# preload 대상 서비스 코드
|
||||
service-code: "example-service"
|
||||
# 서버 시작 시 API Key 캐시 적재 여부
|
||||
preload-on-startup: true
|
||||
# 내부 관리용 API 노출 여부
|
||||
preload-on-startup: false
|
||||
admin-api-enabled: false
|
||||
admin-allow-ips:
|
||||
# 내부 관리 API 접근 허용 CIDR
|
||||
- "127.0.0.1/32"
|
||||
- "localhost"
|
||||
- "0:0:0:0:0:0:0:1"
|
||||
db:
|
||||
# API Key 전용 DB 접속 URL
|
||||
url: "jdbc:mysql://localhost:3306/kri_common"
|
||||
# API Key 전용 DB 계정
|
||||
url: "jdbc:mysql://localhost:3306/kri_common?characterEncoding=UTF-8"
|
||||
username: "app"
|
||||
# API Key 전용 DB 비밀번호
|
||||
password: "secret"
|
||||
# JDBC 드라이버 클래스
|
||||
driver-class-name: "com.mysql.cj.jdbc.Driver"
|
||||
jpa:
|
||||
# Hibernate SQL 로그 출력 여부
|
||||
show-sql: false
|
||||
# Hibernate SQL 포맷팅 여부
|
||||
format-sql: false
|
||||
security:
|
||||
# 기본 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:
|
||||
# Swagger/OpenAPI 자동구성 활성화
|
||||
enabled: true
|
||||
# 문서 타이틀
|
||||
title: "Example API"
|
||||
# 문서 설명
|
||||
description: "Example API Docs"
|
||||
# 문서 버전 표시값
|
||||
title: "KRI API"
|
||||
description: "KRI Common API Docs"
|
||||
version: "v1"
|
||||
# Swagger 스캔 대상 base package
|
||||
base-package: "com.example.api"
|
||||
base-package:
|
||||
- "com.example.api"
|
||||
allowed-ips:
|
||||
# Swagger UI / API Docs 접근 허용 IP
|
||||
- "127.0.0.1"
|
||||
- "localhost"
|
||||
web:
|
||||
# 공통 웹 예외/trace 필터 활성화
|
||||
enabled: true
|
||||
mdc:
|
||||
# handler/service MDC 기록 활성화
|
||||
enabled: true
|
||||
redis:
|
||||
# Redis 보조 기능 활성화
|
||||
enabled: true
|
||||
enabled: false
|
||||
scheduling:
|
||||
# @Scheduled 사용을 위한 스케줄링 활성화
|
||||
enabled: true
|
||||
enabled: false
|
||||
error:
|
||||
expose:
|
||||
# 에러 응답에 handler 정보 포함 여부
|
||||
handler: false
|
||||
# 에러 응답에 service 정보 포함 여부
|
||||
service: false
|
||||
```
|
||||
|
||||
### 항목별 정리
|
||||
운영 서비스에서는 JWT secret, API Key DB 접속 정보, Swagger/API Key admin 허용 IP를 반드시 서비스 환경에 맞게 override해야 합니다.
|
||||
|
||||
#### `kri.auth.jwt`
|
||||
### `kri.auth.jwt`
|
||||
|
||||
- 대상: JWT 생성/검증
|
||||
- 사용 대상 클래스: `JwtAutoConfiguration`, `JwtProperties`, `JwtService`
|
||||
- 설명: issuer, access/refresh 만료 시간, JWT secret을 제어합니다.
|
||||
관련 클래스:
|
||||
|
||||
#### `kri.auth.apikey`
|
||||
- `JwtAutoConfiguration`
|
||||
- `JwtProperties`
|
||||
- `JwtService`
|
||||
|
||||
- 대상: API Key 인증, preload 캐시, 내부 관리용 endpoint
|
||||
- 사용 대상 클래스: `ApiKeyJpaAutoConfiguration`, `ApiKeyPreloadAutoConfiguration`, `ApiKeyAdminAutoConfiguration`
|
||||
- 설명: API Key 헤더, preload, admin API 노출, 전용 DB 연결을 제어합니다.
|
||||
기능:
|
||||
|
||||
#### `kri.security`
|
||||
- `JwtProperties`를 바탕으로 `JwtService` Bean 등록
|
||||
- access token, refresh token 유효 시간 설정
|
||||
- issuer, HMAC secret 설정
|
||||
|
||||
- 대상: 기본 Spring Security 필터체인
|
||||
- 사용 대상 클래스: `KriSecurityAutoConfiguration`, `KriSecurityProperties`
|
||||
- 설명: 공개 경로와 JWT/API Key 필터 적용 여부를 제어합니다.
|
||||
기본값은 개발 편의를 위한 값이므로 운영에서는 `secret`을 반드시 교체해야 합니다.
|
||||
|
||||
#### `kri.swagger`
|
||||
### `kri.auth.apikey`
|
||||
|
||||
- 대상: OpenAPI 문서, Swagger 접근 제어
|
||||
- 사용 대상 클래스: `KriSwaggerAutoConfiguration`, `KriSwaggerProperties`
|
||||
- 설명: 문서 메타정보와 스캔 패키지, 허용 IP를 제어합니다.
|
||||
관련 클래스:
|
||||
|
||||
#### `kri.web`
|
||||
- `ApiKeyProperties`
|
||||
- `ApiKeyJpaAutoConfiguration`
|
||||
- `ApiKeyPreloadAutoConfiguration`
|
||||
- `ApiKeyAdminAutoConfiguration`
|
||||
- `ApiKeyAuthFilter`
|
||||
- `PreloadedApiKeyUserClaimsProvider`
|
||||
|
||||
- 대상: 공통 예외 응답, traceId, MDC
|
||||
- 사용 대상 클래스: `CommonWebAutoConfiguration`
|
||||
- 설명: `ErrorAdvice`, `TraceFilter`, MDC 관련 구성을 켜고 끕니다.
|
||||
기능:
|
||||
|
||||
- `enabled=true`일 때 API Key 인증 기능 활성화
|
||||
- `header-name`으로 API Key를 읽을 HTTP header 지정
|
||||
- JPA repository를 통해 서비스별 활성 API Key를 preload cache로 적재
|
||||
- `ApiKeyAuthFilter`가 API Key를 `Authentication`으로 변환
|
||||
- `admin-api-enabled=true`일 때 내부 reload/cache endpoint 노출
|
||||
|
||||
#### `kri.redis`
|
||||
주의:
|
||||
|
||||
- 대상: Redis 큐 헬퍼
|
||||
- 사용 대상 클래스: `CommonRedisAutoConfiguration`
|
||||
- 설명: Redis 연결 빈이 있을 때 `RedisQueueHelper`를 자동 등록합니다.
|
||||
- DB preload 방식은 JPA와 DataSource 관련 classpath가 필요합니다.
|
||||
- `service-code`가 비어 있으면 preload cache는 비어 있게 됩니다.
|
||||
- admin API는 IP allowlist를 통과해야 합니다.
|
||||
|
||||
#### `kri.scheduling`
|
||||
### `kri.security`
|
||||
|
||||
- 대상: 스케줄링 활성화
|
||||
- 사용 대상 클래스: `CommonSchedulingAutoConfiguration`
|
||||
- 설명: 서비스에서 `@Scheduled`를 사용할 수 있게 합니다.
|
||||
`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.
|
||||
|
||||
#### `kri.error.expose.*`
|
||||
관련 클래스:
|
||||
|
||||
- 대상: 에러 응답의 MDC 부가 정보 노출
|
||||
- 사용 대상 클래스: `ErrorAdvice`
|
||||
- 설명: handler, service 정보를 응답에 포함할지 제어합니다.
|
||||
- `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 설명 보강
|
||||
|
||||
### `kri.web`
|
||||
|
||||
관련 클래스:
|
||||
|
||||
- `CommonWebAutoConfiguration`
|
||||
- `ErrorAdvice`
|
||||
- `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`
|
||||
|
||||
---
|
||||
|
||||
## 자동 구성에 의해 동작하는 내부 런타임 구성요소
|
||||
|
||||
아래 패키지는 서비스에서 직접 import해서 쓰기보다는, 자동 구성에 의해 조립되어 동작하는 내부 구현입니다.
|
||||
|
||||
- `com.kri.common.runtime.auth.apikey`
|
||||
- `ApiKeyAuthFilter`
|
||||
- `PreloadedApiKeyUserClaimsProvider`
|
||||
- `persistence.entity`
|
||||
- `persistence.repository`
|
||||
- `com.kri.common.runtime.security`
|
||||
- `JwtAuthenticationFilter`
|
||||
- `com.kri.common.runtime.swagger`
|
||||
- `SwaggerIpFilter`
|
||||
- `com.kri.common.runtime.web`
|
||||
- `CodeEnumConverter`
|
||||
- `ErrorAdvice`
|
||||
- `IpUtil`
|
||||
- `RequestUserContextArgumentResolver`
|
||||
- `TraceFilter`
|
||||
- `ServiceMdcAspect`
|
||||
|
||||
---
|
||||
|
||||
|
||||
## 자동 노출 endpoint
|
||||
|
||||
#### `com.kri.common.endpoint.auth.apikey.ApiKeyAdminController`
|
||||
### API Key admin
|
||||
|
||||
- 노출 조건: `kri.auth.apikey.admin-api-enabled=true` 그리고 `PreloadedApiKeyUserClaimsProvider` 빈 존재
|
||||
- 경로: `/internal/apikey/reload`, `/internal/apikey/cache`
|
||||
- 설명: preload 캐시 재적재와 현재 캐시 조회를 위한 내부 관리용 endpoint입니다.
|
||||
클래스:
|
||||
|
||||
- `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`
|
||||
|
||||
---
|
||||
|
||||
## AutoConfiguration 목록
|
||||
## 자동 구성 목록
|
||||
|
||||
`src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`
|
||||
자동 구성 목록은 `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`
|
||||
@@ -331,8 +583,12 @@ kri:
|
||||
|
||||
---
|
||||
|
||||
## 검토 메모
|
||||
## 사용 시 권장 기준
|
||||
|
||||
- `ApiKeyProperties`의 DB 기본값, `JwtProperties`의 secret 기본값은 의도적으로 유지 중입니다.
|
||||
- 문서 기준 패키지명은 현재 리팩터링 결과인 `autoconfigure / feature / runtime / endpoint`를 따릅니다.
|
||||
- 컴파일 검증은 `.\gradlew.bat compileJava` 기준으로 통과했습니다.
|
||||
- 서비스 코드에서는 가능한 한 `feature` 패키지의 타입만 직접 사용합니다.
|
||||
- `runtime` 패키지는 자동 구성으로 조립되는 내부 구현으로 보고 직접 의존을 피합니다.
|
||||
- 운영 환경에서는 기본 JWT secret과 API Key DB 설정을 사용하지 않습니다.
|
||||
- 자체 보안 정책이 필요한 서비스는 직접 `SecurityFilterChain` Bean을 등록해 기본 구성을 대체합니다.
|
||||
- Swagger 접근 제한은 운영망/관리망 정책에 맞춰 `allowed-ips`를 명시합니다.
|
||||
- 대용량 Excel은 일반 `Workbook` 변환보다 streaming API를 우선 검토합니다.
|
||||
- 배포 전 `./gradlew compileJava`로 컴파일을 확인합니다.
|
||||
|
||||
@@ -4,7 +4,7 @@ plugins {
|
||||
}
|
||||
|
||||
// 버전 변경은 여기서
|
||||
def commonVer = "beta.1.1.32"
|
||||
def commonVer = "beta.1.1.33"
|
||||
|
||||
group = 'com.kri.common'
|
||||
version = commonVer
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.kri.common.autoconfigure.security;
|
||||
|
||||
import com.kri.common.runtime.auth.apikey.ApiKeyAuthFilter;
|
||||
import com.kri.common.feature.auth.jwt.JwtService;
|
||||
import com.kri.common.runtime.security.IpAllowlistAuthorizationManager;
|
||||
import com.kri.common.runtime.security.JwtAuthenticationFilter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
@@ -11,12 +12,15 @@ 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.authorization.AuthenticatedAuthorizationManager;
|
||||
import org.springframework.security.authorization.AuthorizationDecision;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@AutoConfiguration(before = SecurityAutoConfiguration.class)
|
||||
@@ -49,6 +53,9 @@ public class KriSecurityAutoConfiguration {
|
||||
JwtAuthenticationFilter jwtAuthenticationFilter
|
||||
) throws Exception {
|
||||
|
||||
IpAllowlistAuthorizationManager ipAllowlist =
|
||||
new IpAllowlistAuthorizationManager(securityProperties.getAllowedIps());
|
||||
|
||||
http
|
||||
.httpBasic(AbstractHttpConfigurer::disable)
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
@@ -60,11 +67,27 @@ public class KriSecurityAutoConfiguration {
|
||||
// ✅ yaml에서 정의한 public-paths 전부 permitAll
|
||||
if (securityProperties.getPublicPaths() != null && !securityProperties.getPublicPaths()
|
||||
.isEmpty()) {
|
||||
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new))
|
||||
.permitAll();
|
||||
if (ipAllowlist.isConfigured()) {
|
||||
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new))
|
||||
.access(ipAllowlist);
|
||||
} else {
|
||||
auth.requestMatchers(securityProperties.getPublicPaths().toArray(String[]::new))
|
||||
.permitAll();
|
||||
}
|
||||
}
|
||||
// ✅ 나머지는 전부 인증 필요
|
||||
auth.anyRequest().authenticated();
|
||||
if (ipAllowlist.isConfigured()) {
|
||||
auth.anyRequest().access((authentication, context) -> {
|
||||
AuthorizationDecision ipDecision = ipAllowlist.check(authentication, context);
|
||||
if (ipDecision == null || !ipDecision.isGranted()) {
|
||||
return new AuthorizationDecision(false);
|
||||
}
|
||||
return AuthenticatedAuthorizationManager.<RequestAuthorizationContext>authenticated()
|
||||
.check(authentication, context);
|
||||
});
|
||||
} else {
|
||||
auth.anyRequest().authenticated();
|
||||
}
|
||||
});
|
||||
|
||||
// ✅ API Key 필터가 존재하면 먼저 태움
|
||||
|
||||
@@ -23,4 +23,9 @@ public class KriSecurityProperties {
|
||||
"/swagger-ui.html",
|
||||
"/swagger-ui/**"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* IP allowlist applied by the default SecurityFilterChain. Empty means no IP restriction.
|
||||
*/
|
||||
private List<String> allowedIps = List.of();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.kri.common.runtime.security;
|
||||
|
||||
import com.kri.common.runtime.web.IpUtil;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
import org.springframework.security.authorization.AuthorizationDecision;
|
||||
import org.springframework.security.authorization.AuthorizationManager;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
|
||||
import org.springframework.security.web.util.matcher.IpAddressMatcher;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
public class IpAllowlistAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
|
||||
|
||||
private final List<AllowedIp> allowedIps;
|
||||
|
||||
public IpAllowlistAuthorizationManager(List<String> allowedIps) {
|
||||
this.allowedIps = allowedIps == null ? List.of() : allowedIps.stream()
|
||||
.filter(StringUtils::hasText)
|
||||
.map(String::trim)
|
||||
.map(AllowedIp::new)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public boolean isConfigured() {
|
||||
return !allowedIps.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthorizationDecision check(
|
||||
Supplier<Authentication> authentication,
|
||||
RequestAuthorizationContext context
|
||||
) {
|
||||
HttpServletRequest request = context.getRequest();
|
||||
String clientIp = IpUtil.getClientIp(request);
|
||||
boolean granted = allowedIps.stream().anyMatch(allowedIp -> allowedIp.matches(clientIp));
|
||||
return new AuthorizationDecision(granted);
|
||||
}
|
||||
|
||||
private static class AllowedIp {
|
||||
|
||||
private final boolean localhost;
|
||||
private final IpAddressMatcher matcher;
|
||||
|
||||
private AllowedIp(String value) {
|
||||
this.localhost = "localhost".equalsIgnoreCase(value);
|
||||
this.matcher = localhost ? null : new IpAddressMatcher(value);
|
||||
}
|
||||
|
||||
private boolean matches(String clientIp) {
|
||||
if (localhost) {
|
||||
return "localhost".equalsIgnoreCase(clientIp)
|
||||
|| "127.0.0.1".equals(clientIp)
|
||||
|| "0:0:0:0:0:0:0:1".equals(clientIp)
|
||||
|| "::1".equals(clientIp);
|
||||
}
|
||||
return matcher.matches(clientIp);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user