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
./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

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

import com.kri.common.feature.auth.apikey.ApiKeyUserClaimsProvider;

API Key를 JwtUserClaimsDto로 매핑하는 확장 인터페이스입니다.

Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey);

서비스에서 직접 구현한 Bean을 등록하거나, kri.auth.apikey.enabled=true와 JPA 관련 classpath/설정을 통해 DB preload 기반 provider를 사용할 수 있습니다.

요청 사용자 컨텍스트

RequestUserContext

import com.kri.common.feature.web.RequestUserContext;

컨트롤러 파라미터로 선언하면 현재 인증 사용자와 client IP를 받을 수 있습니다. JwtService Bean이 있을 때 RequestUserContextArgumentResolver가 자동 등록됩니다.

@GetMapping("/me")
public Object me(RequestUserContext user) {
  return user;
}

필드는 userId, userCmpn, userTeam, userName, userRole, clientIp이며, isAuthenticated()는 userId != null일 때 true를 반환합니다.

예외/페이징

BusinessException

서비스 레이어에서 HTTP 상태, 에러 코드, 메시지, 부가 정보를 함께 담아 던지는 런타임 예외입니다.

throw BusinessException.badRequest("INVALID_INPUT", "입력값이 올바르지 않습니다.");

팩토리 메서드:

  • badRequest
  • unauthorized
  • forbidden
  • notFound
  • conflict
  • validationError
  • internalError
  • of

with(String key, Object value)로 응답에 포함할 부가 정보를 추가할 수 있습니다.

PageRequestDto, Pageables, PageResponseDto

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

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입니다.

ExternalApiClient client = new ExternalApiClient();
ExternalApiResponse res = client.post(url, headers, jsonBody);

지원 메서드:

  • get
  • delete
  • post
  • put
  • patch

응답은 statusCode, headers, body를 제공합니다.

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 등을 처리할 수 있습니다.

패키지:

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;

설정 예:

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 예:

@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 목록에 연결합니다.

@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가 마지막입니다.

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는 전달하지 않습니다.

JSON

JsonUtil

Jackson ObjectMapper를 명시적으로 받아 JSON 변환을 수행하는 static helper입니다.

  • toMap
  • parseJsonToMap
  • toJson
  • toPrettyJson
  • fromJson
  • deepCopy
  • convert

Excel

ExcelColumn

DTO 필드와 Excel 컬럼을 매핑하는 애너테이션입니다.

@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

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입니다.

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로 설정하는 자동 구성

전체 예시

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"
      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
  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.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 지정
  • JPA repository를 통해 서비스별 활성 API Key를 preload cache로 적재
  • ApiKeyAuthFilter가 API Key를 Authentication으로 변환
  • admin-api-enabled=true일 때 내부 reload/cache endpoint 노출

주의:

  • DB preload 방식은 JPA와 DataSource 관련 classpath가 필요합니다.
  • 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 설명 보강

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

자동 노출 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

사용 시 권장 기준

  • 서비스 코드에서는 가능한 한 feature 패키지의 타입만 직접 사용합니다.
  • runtime 패키지는 자동 구성으로 조립되는 내부 구현으로 보고 직접 의존을 피합니다.
  • 운영 환경에서는 기본 JWT secret과 API Key DB 설정을 사용하지 않습니다.
  • 자체 보안 정책이 필요한 서비스는 직접 SecurityFilterChain Bean을 등록해 기본 구성을 대체합니다.
  • Swagger 접근 제한은 운영망/관리망 정책에 맞춰 allowed-ips를 명시합니다.
  • 대용량 Excel은 일반 Workbook 변환보다 streaming API를 우선 검토합니다.
  • 배포 전 ./gradlew compileJava로 컴파일을 확인합니다.
Description
No description provided
Readme 1 MiB
Languages
Java 100%