From 4bbcbedc7d7729c76dd1d8012109d7fa37b69364 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Fri, 14 Nov 2025 12:17:18 +0900 Subject: [PATCH] =?UTF-8?q?251114=5F01=5FENH=20:=20JWT,=20API-Key=20?= =?UTF-8?q?=EA=B8=B0=EB=8A=A5=20=EC=B6=94=EA=B0=80,=20README=20=EC=9E=91?= =?UTF-8?q?=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/git_toolbox_prj.xml | 15 + README.md | 618 ++++++++++++++++++ build.gradle | 47 +- gradle.properties | 2 + .../common/auth/apikey/ApiKeyAuthFilter.java | 58 ++ .../common/auth/apikey/ApiKeyProperties.java | 22 + .../auth/apikey/ApiKeyUserClaimsProvider.java | 19 + .../common/auth/jwt/JwtAutoConfiguration.java | 34 + .../kri/common/auth/jwt/JwtProperties.java | 62 ++ .../com/kri/common/auth/jwt/JwtService.java | 216 ++++++ .../kri/common/auth/jwt/JwtUserClaimsDto.java | 26 + ...ot.autoconfigure.AutoConfiguration.imports | 3 +- 12 files changed, 1112 insertions(+), 10 deletions(-) create mode 100644 .idea/git_toolbox_prj.xml create mode 100644 README.md create mode 100644 gradle.properties create mode 100644 src/main/java/com/kri/common/auth/apikey/ApiKeyAuthFilter.java create mode 100644 src/main/java/com/kri/common/auth/apikey/ApiKeyProperties.java create mode 100644 src/main/java/com/kri/common/auth/apikey/ApiKeyUserClaimsProvider.java create mode 100644 src/main/java/com/kri/common/auth/jwt/JwtAutoConfiguration.java create mode 100644 src/main/java/com/kri/common/auth/jwt/JwtProperties.java create mode 100644 src/main/java/com/kri/common/auth/jwt/JwtService.java create mode 100644 src/main/java/com/kri/common/auth/jwt/JwtUserClaimsDto.java diff --git a/.idea/git_toolbox_prj.xml b/.idea/git_toolbox_prj.xml new file mode 100644 index 0000000..02b915b --- /dev/null +++ b/.idea/git_toolbox_prj.xml @@ -0,0 +1,15 @@ + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..d7546f7 --- /dev/null +++ b/README.md @@ -0,0 +1,618 @@ +# KriCommon Starter + +Spring Boot 기반 사내 서비스에서 공통으로 사용하는 기능들을 모아둔 라이브러리입니다. +`example-service` 같은 개별 서비스는 이 라이브러리를 통해 다음과 같은 기능을 **일관된 방식으로 재사용**할 수 있습니다. + +- JWT 기반 인증/인가 (`com.kri.common.auth.jwt`) +- 내부 고정 토큰 처리 +- 외부 API Key 인증 (`com.kri.common.auth.apikey`) +- 공통 Web 예외 처리 & 로깅 (`com.kri.common.web`) +- Redis 큐 헬퍼 (`com.kri.common.redis`) +- 스케줄링 활성화 (`com.kri.common.scheduling`) +- 기본 logback 설정 + +이 문서는 **KriCommon을 사용하는 서비스(example-service)** 기준으로 작성되었습니다. + +--- + +## 1. 환경 요구사항 + +- **Java 17** +- **Spring Boot 3.5.x** + (KriCommon 내부 BOM: `org.springframework.boot:spring-boot-dependencies:3.5.7`) +- **Servlet 기반 Spring MVC** (WebFlux 미지원) + +--- + +## 2. 의존성 추가 + +### 2.1. Gitea Maven Registry 설정 + +`example-service/build.gradle`: + +```groovy +repositories { + mavenCentral() + + maven { + name = "gitea" + url = uri("http://10.10.10.11:3000/api/packages/KRi/maven") + allowInsecureProtocol = true + credentials { + username = findProperty("giteaUser") ?: "" + password = findProperty("giteaToken") ?: "" + } + } +} +``` + +`gradle.properties` (루트 또는 사용자 홈): + +```properties +giteaUser=gitadmin +giteaToken=YOUR_GITEA_TOKEN # 실제 토큰으로 교체 +``` + +> **Tip** +> - 토큰을 깃이나 공유 저장소에 올리지 않도록 주의하세요. +> - 실제로는 환경 변수 또는 CI/CD 시크릿을 사용해 주입하는 것을 권장합니다. + +### 2.2. Starter 라이브러리 의존성 + +```groovy +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' + implementation 'org.springframework.boot:spring-boot-starter-aop' + implementation 'org.springframework.boot:spring-boot-starter-data-redis' + + // Swagger / OpenAPI (선택, 문서화용) + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0' + + // ✅ KriCommon Starter + implementation 'com.kri.common:starter:1.0.1' +} +``` + +--- + +## 3. 구성 요소 개요 + +KriCommon 은 크게 5가지 축으로 나뉩니다. + +1. **인증/인가** + - JWT, 내부 고정 토큰, API Key를 모두 공통 DTO(`JwtUserClaimsDto`) 기반으로 정규화 +2. **Web 공통 기능** + - 예외 처리, traceId/MDC, AOP 기반 service/handler 로깅 +3. **Redis 큐 지원** + - 간단한 Redis List 기반 큐 컨슈머/프로듀서 유틸 +4. **스케줄링 활성화** + - 서비스에서 직접 `@EnableScheduling` 선언 없이 property 로 on/off +5. **로깅/Logback 기본 설정** + - traceId, service, handler, thread 정보가 통일된 패턴으로 출력 + +각 기능은 **프로퍼티 + AutoConfiguration + 유틸 Bean** 조합으로 제공되며, +서비스는 필요한 부분만 선택적으로 활성화하면 됩니다. + +--- + +## 4. 설정 예시 (application.yml) + +`example-service/src/main/resources/application.yml` 기본 예시는 다음과 같습니다. + +```yaml +server: + port: 8080 + +spring: + application: + name: example-service + +logging: + file: + path: ./logs + +kri: + auth: + jwt: + secret: "CHANGE_ME_TO_A_SECURE_SECRET_32+CHARS" + issuer: "kri-it" + + # 내부 시스템 간 통신에 사용할 고정 토큰 (선택) + internal-fixed-token: "VERY_SECURE_INTERNAL_TOKEN_VALUE" + + # 고정 토큰 사용 시 SecurityContext 에 올릴 기본 계정정보 + internal-user-id: "SYSTEM_EXAMPLE" + internal-user-team: "IT" + internal-user-name: "Example Internal System" + internal-user-role: 999 + + apikey: + enabled: true # API Key 인증 사용 여부 + header-name: "X-API-Key" # API Key 헤더 이름 + +common: + web: + enabled: true # 공통 Web 구성 사용 여부 (기본 true) + redis: + enabled: false # RedisQueueHelper 사용 시 true + scheduling: + enabled: false # @Scheduled 사용 시 true +``` + +### 4.1. `kri.auth.jwt` 속성 요약 + +| 프로퍼티 | 타입 | 기본값 | 설명 | +| ---------------------------------------- | -------- | ---------------------------------- | ---- | +| `kri.auth.jwt.secret` | String | (기본값 있음, 서비스에서 override 권장) | HMAC 서명에 사용할 시크릿 키 (최소 32자 이상) | +| `kri.auth.jwt.issuer` | String | `"kri-it"` | 토큰 발급자(issuer) | +| `kri.auth.jwt.access-token-validity-seconds` | long | `24 * 3600` | Access Token 유효 시간(초) | +| `kri.auth.jwt.refresh-token-validity-seconds` | long | `7 * 24 * 3600` | Refresh Token 유효 시간(초) | +| `kri.auth.jwt.internal-fixed-token` | String | `null` | 내부 고정 토큰 문자열 (null이면 미사용) | +| `kri.auth.jwt.internal-user-id` | String | `"INTERNAL_SYSTEM"` | 내부 토큰 계정 userId | +| `kri.auth.jwt.internal-user-team` | String | `"SYSTEM"` | 내부 토큰 계정 team | +| `kri.auth.jwt.internal-user-name` | String | `"Internal System"` | 내부 토큰 계정 이름 | +| `kri.auth.jwt.internal-user-role` | Integer | `999` | 내부 토큰 계정 role 코드 | + +### 4.2. `kri.auth.apikey` 속성 요약 + +| 프로퍼티 | 타입 | 기본값 | 설명 | +| ------------------------------ | ------- | ---------- | ---- | +| `kri.auth.apikey.enabled` | boolean | `false` | API Key 인증 기능 활성화 여부 | +| `kri.auth.apikey.header-name` | String | `X-API-Key`| API Key 를 읽을 HTTP 헤더 이름 | + +### 4.3. `common.*` 속성 요약 + +| 프로퍼티 | 타입 | 기본값 | 설명 | +| -------------------------- | ------- | ------ | ---- | +| `common.web.enabled` | boolean | `true` | Web 예외/로깅/필터 자동 구성 여부 | +| `common.redis.enabled` | boolean | `false`| RedisQueueHelper 자동 구성 여부 | +| `common.scheduling.enabled`| boolean | `false`| `@EnableScheduling` 자동 적용 여부 | + +--- + +## 5. JWT 기능 상세 (`com.kri.common.auth.jwt`) + +### 5.1. JwtUserClaimsDto + +JWT 에 들어가는 **표준 Payload** 를 정의하는 DTO입니다. + +```java +@Schema( + name = "JwtUserClaimsDto", + description = "JWT에 포함되는 사용자 정보 (T_USER 기준)" +) +@Value +@Builder +public class JwtUserClaimsDto { + + @Schema(description = "사용자 ID (T_USER.USER_ID)") + String userId; + + @Schema(description = "팀 코드 또는 팀명 (T_USER.USER_TEAM)") + String userTeam; + + @Schema(description = "사용자 이름 (T_USER.USER_NM)") + String userName; + + @Schema(description = "권한 코드 (T_USER.ROLL, INTEGER)") + Integer role; +} +``` + +> Swagger/OpenAPI 를 사용하는 서비스에서는 +> 이 DTO를 반환 타입이나 요청 타입에 사용하면 자동으로 문서화됩니다. + +### 5.2. JwtService 주요 메서드 + +JwtService 는 다음과 같은 역할을 합니다. + +1. **Access Token 발급** +2. **Refresh Token 발급** +3. **토큰 파싱 및 검증** +4. **토큰 → JwtUserClaimsDto/Authentication 변환** +5. **내부 고정 토큰 처리** + +핵심 메서드 요약: + +```java +public class JwtService { + + // Access Token 생성 + public String generateAccessToken(JwtUserClaimsDto userClaims); + + // Refresh Token 생성 (subject = userId) + public String generateRefreshToken(String userId); + + // 토큰 파싱 + 서명/만료 검증 + public Jws parseToken(String token) throws JwtException; + + // Claims 추출 + public Claims getClaims(String token) throws JwtException; + + // Claims -> DTO + public JwtUserClaimsDto toUserClaimsDto(Claims claims); + + // 토큰 -> DTO + public JwtUserClaimsDto toUserClaimsDto(String token) throws JwtException; + + // DTO -> Authentication (Spring Security) + public Authentication toAuthentication(JwtUserClaimsDto dto); + + // 토큰 -> Authentication + public Authentication toAuthentication(String token) throws JwtException; + + // 내부 고정 토큰인지 확인 + public boolean isInternalFixedToken(String rawToken); + + // 내부 고정 토큰용 DTO / Authentication 생성 + public JwtUserClaimsDto createInternalUserClaimsDto(); + public Authentication createInternalAuthentication(); +} +``` + +### 5.3. 로그인 흐름 예시 + +```java +@Service +@RequiredArgsConstructor +public class AuthService { + + private final JwtService jwtService; + + public String login(String userId, String password) { + // 1) userId/password 검증 및 T_USER 조회 + // 예시용 더미 값 + String userTeam = "TEAM_A"; + String userName = "홍길동"; + Integer role = 1; + + JwtUserClaimsDto claims = JwtUserClaimsDto.builder() + .userId(userId) + .userTeam(userTeam) + .userName(userName) + .role(role) + .build(); + + // 2) Access Token 발급 + return jwtService.generateAccessToken(claims); + } +} +``` + +### 5.4. JWT 인증 필터 예시 (서비스 측 구현) + +KriCommon 은 **JwtAuthenticationFilter 구현은 제공하지 않습니다.** +서비스마다 요구사항이 다르기 때문에, +아래와 같이 `JwtService` 를 사용하는 커스텀 필터를 작성해 연결하는 방식을 권장합니다. + +```java +@RequiredArgsConstructor +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + private final JwtService jwtService; + + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain) + throws ServletException, IOException { + + if (SecurityContextHolder.getContext().getAuthentication() == null) { + String header = request.getHeader("Authorization"); + if (header != null && header.startsWith("Bearer ")) { + String token = header.substring("Bearer ".length()); + + Authentication auth; + if (jwtService.isInternalFixedToken(token)) { + auth = jwtService.createInternalAuthentication(); + } else { + auth = jwtService.toAuthentication(token); + } + + SecurityContextHolder.getContext().setAuthentication(auth); + } + } + + filterChain.doFilter(request, response); + } +} +``` + +SecurityConfig 에 등록: + +```java +http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); +``` + +--- + +## 6. API Key 인증 (`com.kri.common.auth.apikey`) + +### 6.1. 설계 개요 + +- 외부 시스템에서 발급한 API Key가 `X-API-Key` 헤더로 들어오는 경우를 처리하기 위한 기능입니다. +- KriCommon 은: + - 헤더에서 Key를 읽고 + - `ApiKeyUserClaimsProvider` 에 Key를 전달하여 + - 유효한 경우 `JwtUserClaimsDto` → `Authentication` 을 생성해 SecurityContext에 세팅합니다. +- 각 서비스는 **오직 "이 Key가 누구 것인지"만 구현**하면 됩니다. + +### 6.2. ApiKeyUserClaimsProvider (서비스에서 구현) + +```java +public interface ApiKeyUserClaimsProvider { + + /** + * API Key 로 사용자 정보를 조회한다. + * + * @param apiKey 요청 헤더에서 받은 API Key + * @return 유효한 키면 JwtUserClaimsDto, 아니면 Optional.empty() + */ + Optional findUserByApiKey(String apiKey); +} +``` + +구현 예시: + +```java +@Service +@RequiredArgsConstructor +public class ApiKeyUserClaimsProviderImpl implements ApiKeyUserClaimsProvider { + + // private final ApiKeyMapper apiKeyMapper; + + @Override + public Optional findUserByApiKey(String apiKey) { + // TODO: DB 조회(MyBatis)로 교체 + if ("EXTERNAL_KEY_1".equals(apiKey)) { + return Optional.of( + JwtUserClaimsDto.builder() + .userId("partnerA") + .userTeam("EXT") + .userName("외부 파트너 A") + .role(10) + .build() + ); + } + return Optional.empty(); + } +} +``` + +### 6.3. ApiKeyAuthFilter (공통 필터) + +KriCommon 에서 제공하는 필터는 다음과 같이 동작합니다. + +1. `kri.auth.apikey.enabled=false` 이면 아무 작업도 하지 않음 +2. 이미 SecurityContext에 Authentication 이 있으면 패스 +3. 설정된 헤더(`kri.auth.apikey.header-name`)에서 Key를 읽음 +4. `ApiKeyUserClaimsProvider` 로 조회 +5. DTO가 반환되면 `JwtService.toAuthentication(dto)`로 Authentication 생성 + +서비스 측에서는 단지 **필터를 SecurityConfig 에 추가**하면 됩니다. + +```java +@Configuration +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig { + + private final ApiKeyAuthFilter apiKeyAuthFilter; + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .csrf(csrf -> csrf.disable()) + .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/actuator/health").permitAll() + .anyRequest().authenticated() + ); + + // JWT 필터가 있다면 순서 조정 가능 + http.addFilterBefore(apiKeyAuthFilter, UsernamePasswordAuthenticationFilter.class); + + return http.build(); + } +} +``` + +--- + +## 7. Web 공통 기능 (`com.kri.common.web`) + +### 7.1. ErrorAdvice & BusinessException + +- `BusinessException` 은 비즈니스 로직에서 발생시키는 커스텀 예외입니다. +- `ErrorAdvice` 가 이를 캐치하여 **`ProblemDetail` 기반 JSON 응답**으로 변환합니다. + +사용 예: + +```java +if (!true) { + throw BusinessException.of( + HttpStatus.BAD_REQUEST, + "INVALID_PARAM", + "요청 파라미터가 유효하지 않습니다." + ).with("field", "name"); +} +``` + +응답 예 (대략적인 형태): + +```json +{ + "status": 400, + "title": "INVALID_PARAM", + "detail": "요청 파라미터가 유효하지 않습니다.", + "field": "name", + "traceId": "c5b2b6ab...", + "timestamp": "2025-01-01T12:34:56.789+09:00" +} +``` + +> 실제 필드 구조는 `ErrorAdvice` 구현을 참고하십시오. + +### 7.2. TraceFilter / MDC + +- `TraceFilter` + - 요청마다 `traceId` 를 생성 또는 `X-Request-Id` 헤더에서 재사용 + - MDC 에 `traceId` 세팅 +- `MdcHandlerConfig` + - HandlerInterceptor 를 사용해 `handler` 정보를 MDC에 기록 (`Controller#method`) +- `ServiceMdcAspect` + - `@Service` 메서드 호출 시 `service` MDC 필드에 기록 (`Service#method`) + +이 정보는 기본 logback 패턴(또는 서비스에서 override한 패턴)에 포함되어 +로그 상에서 **요청 단위/메서드 단위 추적**을 쉽게 만들 수 있습니다. + +--- + +## 8. Redis 큐 (`com.kri.common.redis`) + +### 8.1. 활성화 조건 + +- `common.redis.enabled=true` +- `RedisConnectionFactory` Bean 이 존재 + (보통 `spring-boot-starter-data-redis` + `spring.data.redis.*` 설정) + +> 두 조건이 충족되면 `CommonRedisAutoConfiguration` 이 +> `StringRedisTemplate` 및 `RedisQueueHelper` 를 자동으로 등록합니다. + +### 8.2. RedisQueueHelper 사용 예시 + +```java +@Service +@RequiredArgsConstructor +public class JobQueueService { + + private final RedisQueueHelper redisQueueHelper; + + public void enqueueJob(String jobId) { + redisQueueHelper.enqueue("job-queue", jobId); + } + + public String dequeueJob() { + // 최대 5초 동안 대기 + return redisQueueHelper.blockingDequeue("job-queue", Duration.ofSeconds(5)); + } +} +``` + +**권장 패턴** + +- Producer: 서비스/컨트롤러에서 업무 이벤트를 큐에 적재 +- Consumer: @Scheduled 또는 별도 Thread에서 blockingDequeue 로 작업 수행 + +--- + +## 9. 스케줄링 (`com.kri.common.scheduling`) + +### 9.1. 활성화 방법 + +```yaml +common: + scheduling: + enabled: true +``` + +이 설정만 켜면: + +- `CommonSchedulingAutoConfiguration` 이 `@EnableScheduling` 을 적용합니다. +- 서비스 코드에서는 평소처럼 `@Scheduled` 만 선언하면 됩니다. + +예: + +```java +@Component +public class ExampleScheduler { + + @Scheduled(fixedDelay = 10_000) + public void doSomething() { + // 10초마다 실행 + } +} +``` + +> 장점: +> - 서비스마다 `@EnableScheduling` 애노테이션 중복 선언을 피할 수 있음 +> - 프로퍼티로 스케줄링 on/off 제어가 쉬워짐 + +--- + +## 10. 로깅 / logback + +KriCommon 은 기본적인 `logback-spring.xml` 을 제공합니다. + +- 콘솔 로그 + 파일 로그(rolling) +- MDC 값 포함: + - `traceId` + - `handler` (Controller 메서드) + - `service` (Service 메서드) + - thread, level, logger 등 + +서비스에서 **직접 `logback-spring.xml` 을 제공하면 해당 설정이 우선 적용**되므로, +필요하면 KriCommon의 설정을 복사 후 서비스에 맞게 수정해서 사용하는 것을 권장합니다. + +--- + +## 11. Swagger / OpenAPI + +KriCommon 의 일부 DTO(`JwtUserClaimsDto` 등)에는 +`io.swagger.v3.oas.annotations.media.Schema` 어노테이션이 포함되어 있습니다. + +`example-service` 에서 springdoc-openapi 를 사용한다면, +다음과 같이 사용할 수 있습니다. + +```java +@RestController +public class MeController { + + @Operation(summary = "현재 로그인 사용자 정보 조회") + @GetMapping("/api/me") + public JwtUserClaimsDto me() { + return JwtUserClaimsDto.builder() + .userId("demo") + .userTeam("TEAM") + .userName("데모 사용자") + .role(1) + .build(); + } +} +``` + +Swagger UI 에서: + +- DTO 이름: `JwtUserClaimsDto` +- 각 필드별 설명: `@Schema(description = "...")` 내용이 그대로 노출됩니다. + +--- + +## 12. 신규 서비스 적용 체크리스트 + +`example-service` 같은 신규 서비스에서 KriCommon 을 사용할 때, +다음 순서대로 점검하면 됩니다. + +1. **Gradle 설정** + - Gitea Maven registry 추가 + - `implementation 'com.kri.common:starter:1.0.1'` 추가 +2. **application.yml** + - `kri.auth.jwt.secret` 최소 32자 이상으로 설정 + - 필요 시 `internal-fixed-token` 및 내부 계정 정보 설정 + - API Key 인증이 필요하면 `kri.auth.apikey.enabled=true` 및 header-name 지정 + - Web/Redis/Scheduling 사용 여부에 따라 `common.*` 설정 +3. **SecurityConfig** + - `ApiKeyAuthFilter` (공통) 필터 체인에 추가 + - JWT 인증이 필요하면 `JwtService` 기반 커스텀 JwtAuthenticationFilter 구현 후 추가 +4. **ApiKeyUserClaimsProvider 구현** + - DB/설정 파일 등에서 API Key → JwtUserClaimsDto 매핑 로직 작성 +5. **로그/예외 확인** + - 의도한 형태로 ProblemDetail, traceId, service/handler 로그가 찍히는지 확인 +6. **Swagger** + - springdoc-openapi 설정 후, 공통 DTO가 API 스펙에 잘 노출되는지 확인 + +이 문서를 기반으로, +각 서비스 팀은 **인증, 로깅, 스케줄링, Redis 큐 구조를 공통 규약에 맞춰 재사용**할 수 있습니다. diff --git a/build.gradle b/build.gradle index e869f35..c96544f 100644 --- a/build.gradle +++ b/build.gradle @@ -3,8 +3,11 @@ plugins { id 'maven-publish' } +//버전 변경은 여기서 +def commonVer = "1.0.2" + group = 'com.kri.common' -version = '1.0.0' +version = commonVer java { toolchain { languageVersion = JavaLanguageVersion.of(17) } @@ -15,26 +18,52 @@ repositories { } dependencies { - // Spring BOM (버전 정합성) - api platform('org.springframework.boot:spring-boot-dependencies:3.5.7') + // 공통 BOM 객체 하나 잡아두고 + def springBootBom = platform('org.springframework.boot:spring-boot-dependencies:3.5.7') - // ★ 자동구성/웹/검증/AOP는 컴파일만 (전이 방지) + // 여기까지가 BOM 적용 구간 + api springBootBom + compileOnly springBootBom + annotationProcessor springBootBom + + // ==== 여기부터는 버전 안 써도 됨 (BOM이 버전 정해줌) ==== + + // JWT + api 'io.jsonwebtoken:jjwt-api:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5' + runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5' + + // Security Core + api 'org.springframework.security:spring-security-core' + + // Swagger / OpenAPI 어노테이션 (@Schema 등) - 컴파일용 + compileOnly 'io.swagger.core.v3:swagger-annotations:2.2.25' + + // Lombok + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + + // ConfigurationProperties 메타데이터 + annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' + compileOnly 'org.springframework.boot:spring-boot-autoconfigure' + + // 자동구성/웹/검증/AOP/Redis는 컴파일만 (전이 방지) compileOnly 'org.springframework.boot:spring-boot-autoconfigure' compileOnly 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.springframework.boot:spring-boot-starter-validation' compileOnly 'org.springframework.boot:spring-boot-starter-aop' - - // ★ Redis 자동구성용 (원하면 끌 수 있게) — 런타임은 소비 앱이 책임 compileOnly 'org.springframework.boot:spring-boot-starter-data-redis' } +def giteaUser = findProperty("giteaUser") ?: "" +def giteaToken = findProperty("giteaToken") ?: "" publishing { publications { release(MavenPublication) { from components.java groupId = 'com.kri.common' artifactId = 'starter' // 소비 프로젝트에서 쓰는 artifactId - version = '1.0.0' + version = commonVer } } repositories { @@ -43,8 +72,8 @@ publishing { url = uri("http://10.10.10.11:3000/api/packages/KRi/maven") // owner=KRi allowInsecureProtocol = true credentials { - username = "gitadmin" // 또는 본인 계정 - password = "8faa3eb482aafec11539696fbcee95604c6b93ee" + username = giteaUser // 또는 본인 계정 + password = giteaToken } } } diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..ed55f67 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,2 @@ +giteaUser=gitadmin +giteaToken=8faa3eb482aafec11539696fbcee95604c6b93ee \ No newline at end of file diff --git a/src/main/java/com/kri/common/auth/apikey/ApiKeyAuthFilter.java b/src/main/java/com/kri/common/auth/apikey/ApiKeyAuthFilter.java new file mode 100644 index 0000000..800135b --- /dev/null +++ b/src/main/java/com/kri/common/auth/apikey/ApiKeyAuthFilter.java @@ -0,0 +1,58 @@ +package com.kri.common.auth.apikey; + +import com.kri.common.auth.jwt.JwtService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +/** + * X-API-Key (또는 설정된 헤더) 기반 API Key 인증 필터. + * - API Key를 검증하는 로직은 ApiKeyUserClaimsProvider 구현체에 위임. + * - 유효하면 JwtUserClaimsDto → Authentication 으로 변환해서 SecurityContext에 세팅. + */ +@RequiredArgsConstructor +public class ApiKeyAuthFilter extends OncePerRequestFilter { + + private final ApiKeyProperties apiKeyProperties; + private final ApiKeyUserClaimsProvider apiKeyUserClaimsProvider; + private final JwtService jwtService; + + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain) + throws ServletException, IOException { + + // API Key 기능이 꺼져 있으면 아무 것도 안 함 + if (!apiKeyProperties.isEnabled()) { + filterChain.doFilter(request, response); + return; + } + + // 이미 다른 방식(JWT 등)으로 인증되어 있으면 패스 + if (SecurityContextHolder.getContext().getAuthentication() != null) { + filterChain.doFilter(request, response); + return; + } + + String headerName = apiKeyProperties.getHeaderName(); + String apiKey = request.getHeader(headerName); + + if (StringUtils.hasText(apiKey)) { + apiKeyUserClaimsProvider.findUserByApiKey(apiKey).ifPresent(dto -> { + Authentication auth = jwtService.toAuthentication(dto); + SecurityContextHolder.getContext().setAuthentication(auth); + }); + } + + filterChain.doFilter(request, response); + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/auth/apikey/ApiKeyProperties.java b/src/main/java/com/kri/common/auth/apikey/ApiKeyProperties.java new file mode 100644 index 0000000..fc68f7b --- /dev/null +++ b/src/main/java/com/kri/common/auth/apikey/ApiKeyProperties.java @@ -0,0 +1,22 @@ +package com.kri.common.auth.apikey; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@Getter +@Setter +@ConfigurationProperties(prefix = "kri.auth.apikey") +public class ApiKeyProperties { + + /** + * API Key 인증 사용 여부 + */ + private boolean enabled = false; + + /** + * API Key 를 읽어올 헤더 이름 + * 예: X-API-Key, X-EXTERNAL-KEY 등 + */ + private String headerName = "X-API-Key"; +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/auth/apikey/ApiKeyUserClaimsProvider.java b/src/main/java/com/kri/common/auth/apikey/ApiKeyUserClaimsProvider.java new file mode 100644 index 0000000..5165bd7 --- /dev/null +++ b/src/main/java/com/kri/common/auth/apikey/ApiKeyUserClaimsProvider.java @@ -0,0 +1,19 @@ +package com.kri.common.auth.apikey; + +import com.kri.common.auth.jwt.JwtUserClaimsDto; +import java.util.Optional; + +/** + * 외부에서 들어온 API Key를 우리 시스템의 유저 정보(JwtUserClaimsDto)로 매핑하는 인터페이스. + * 각 서비스에서 이 인터페이스 구현체를 Bean으로 등록하면 된다. + */ +public interface ApiKeyUserClaimsProvider { + + /** + * API Key 로 사용자 정보를 조회한다. + * + * @param apiKey 요청 헤더에서 받은 API Key + * @return 유효한 키면 JwtUserClaimsDto, 아니면 Optional.empty() + */ + Optional findUserByApiKey(String apiKey); +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/auth/jwt/JwtAutoConfiguration.java b/src/main/java/com/kri/common/auth/jwt/JwtAutoConfiguration.java new file mode 100644 index 0000000..8564aa4 --- /dev/null +++ b/src/main/java/com/kri/common/auth/jwt/JwtAutoConfiguration.java @@ -0,0 +1,34 @@ +package com.kri.common.auth.jwt; + +import com.kri.common.auth.apikey.ApiKeyAuthFilter; +import com.kri.common.auth.apikey.ApiKeyProperties; +import com.kri.common.auth.apikey.ApiKeyUserClaimsProvider; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties({JwtProperties.class, ApiKeyProperties.class}) +public class JwtAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + public JwtService jwtService(JwtProperties properties) { + return new JwtService(properties); + } + + /** + * ApiKeyUserClaimsProvider 구현체가 존재할 때만 API Key 필터 자동 생성. + * (실제 필터 체인에 넣는 건 각 서비스의 SecurityConfig 에서 addFilterBefore 로 수행) + */ + @Bean + @ConditionalOnBean(ApiKeyUserClaimsProvider.class) + @ConditionalOnMissingBean + public ApiKeyAuthFilter apiKeyAuthFilter(ApiKeyProperties apiKeyProperties, + ApiKeyUserClaimsProvider provider, + JwtService jwtService) { + return new ApiKeyAuthFilter(apiKeyProperties, provider, jwtService); + } +} diff --git a/src/main/java/com/kri/common/auth/jwt/JwtProperties.java b/src/main/java/com/kri/common/auth/jwt/JwtProperties.java new file mode 100644 index 0000000..e6f4ed1 --- /dev/null +++ b/src/main/java/com/kri/common/auth/jwt/JwtProperties.java @@ -0,0 +1,62 @@ +package com.kri.common.auth.jwt; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@Getter +@Setter +@ConfigurationProperties(prefix = "kri.auth.jwt") +public class JwtProperties { + + /** + * HMAC 서명에 사용할 시크릿 키 (최소 32자 이상 권장) + */ + private String secret = "K0r2@#R2s2@rch#!nt2rn@t!0n@l#!T$T2@M"; + + /** + * 토큰 발급자(issuer) + */ + private String issuer = "kri-it"; + + /** + * Access Token 유효 시간(초 단위) + */ + private long accessTokenValiditySeconds = 24 * 3600; // 기본 24시간 + + /** + * (선택) Refresh Token 유효 시간(초 단위) + */ + private long refreshTokenValiditySeconds = 7 * 24 * 3600; // 기본 7일 + + // ====================================================== + // 내부 고정 토큰 관련 설정 + // ====================================================== + + /** + * 내부 시스템 간 통신에 사용하는 "고정 토큰" 값 + * - 이 값과 동일한 토큰이 오면 JWT 파싱 없이 내부 계정으로 처리 + */ + private String internalFixedToken; + + /** + * 내부 고정 토큰 사용 시 DTO/Authentication 에 들어갈 사용자 ID + * - T_USER.USER_ID 에 해당 + */ + private String internalUserId = "INTERNAL_SYSTEM"; + + /** + * 내부 고정 토큰 사용 시 DTO/Authentication 에 들어갈 팀 + */ + private String internalUserTeam = "SYSTEM"; + + /** + * 내부 고정 토큰 사용 시 DTO/Authentication 에 들어갈 이름 + */ + private String internalUserName = "Internal System"; + + /** + * 내부 고정 토큰 사용 시 DTO/Authentication 에 들어갈 권한 코드 + */ + private Integer internalUserRole = 1001; +} diff --git a/src/main/java/com/kri/common/auth/jwt/JwtService.java b/src/main/java/com/kri/common/auth/jwt/JwtService.java new file mode 100644 index 0000000..276cb54 --- /dev/null +++ b/src/main/java/com/kri/common/auth/jwt/JwtService.java @@ -0,0 +1,216 @@ +package com.kri.common.auth.jwt; + +import io.jsonwebtoken.*; +import io.jsonwebtoken.security.Keys; +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; + +import javax.crypto.SecretKey; +import java.nio.charset.StandardCharsets; +import java.util.*; + +/** + * 공통 JWT 유틸 서비스 + * - DTO: JwtUserClaimsDto 기준으로 토큰 생성/파싱 + * - 일반 JWT + 내부 고정 토큰 둘 다 지원 + */ +@RequiredArgsConstructor +public class JwtService { + + private final JwtProperties properties; + + private SecretKey key; + + @PostConstruct + public void init() { + // secret 문자열을 HMAC 키로 전환 + this.key = Keys.hmacShaKeyFor( + properties.getSecret().getBytes(StandardCharsets.UTF_8) + ); + } + + // ====================================================== + // 내부 공통 빌더 + // ====================================================== + + private String buildToken(Map claims, String subject, long validitySeconds) { + Date now = new Date(); + Date expiry = new Date(now.getTime() + validitySeconds * 1000); + + return Jwts.builder() + .setClaims(claims) + .setSubject(subject) + .setIssuer(properties.getIssuer()) + .setIssuedAt(now) + .setExpiration(expiry) + .signWith(key, SignatureAlgorithm.HS256) + .compact(); + } + + private Map buildClaims(JwtUserClaimsDto dto) { + Map claims = new HashMap<>(); + // 필요한 항목만 골라서 claim에 넣어줌 + claims.put("userId", dto.getUserId()); + claims.put("userTeam", dto.getUserTeam()); + claims.put("userName", dto.getUserName()); + claims.put("role", dto.getRole()); + return claims; + } + + // ====================================================== + // 토큰 생성 (DTO 기반) + // ====================================================== + + /** + * JwtUserClaimsDto 기반 Access Token 생성 + * - subject = userId + * - claims: + * userId, userTeam, userName, role + */ + public String generateAccessToken(JwtUserClaimsDto userClaims) { + Map claims = buildClaims(userClaims); + return buildToken( + claims, + userClaims.getUserId(), + properties.getAccessTokenValiditySeconds() + ); + } + + /** + * Refresh Token은 보통 userId만 넣고 심플하게 사용 + */ + public String generateRefreshToken(String userId) { + return buildToken( + Collections.emptyMap(), + userId, + properties.getRefreshTokenValiditySeconds() + ); + } + + // ====================================================== + // 토큰 파싱 + // ====================================================== + + /** + * 토큰 파싱 + 서명/만료 검증 + */ + public Jws parseToken(String token) throws JwtException { + return Jwts.parserBuilder() + .requireIssuer(properties.getIssuer()) + .setSigningKey(key) + .build() + .parseClaimsJws(token); + } + + /** + * 토큰에서 Claims만 추출 (검증 포함) + */ + public Claims getClaims(String token) throws JwtException { + return parseToken(token).getBody(); + } + + /** + * Claims → JwtUserClaimsDto 변환 + */ + public JwtUserClaimsDto toUserClaimsDto(Claims claims) { + // userId는 subject와 별도 claim 둘 다에서 시도 + String userId = claims.get("userId", String.class); + if (userId == null) { + userId = claims.getSubject(); + } + + String userTeam = claims.get("userTeam", String.class); + String userName = claims.get("userName", String.class); + + // 숫자는 Integer / Long 등으로 들어올 수 있으니 Number로 받았다가 intValue() + Number roleNumber = claims.get("role", Number.class); + Integer role = roleNumber != null ? roleNumber.intValue() : null; + + return JwtUserClaimsDto.builder() + .userId(userId) + .userTeam(userTeam) + .userName(userName) + .role(role) + .build(); + } + + /** + * 토큰 → JwtUserClaimsDto 바로 추출 + */ + public JwtUserClaimsDto toUserClaimsDto(String token) throws JwtException { + Claims claims = getClaims(token); + return toUserClaimsDto(claims); + } + + // ====================================================== + // Authentication 변환 (Spring Security 연동용) + // ====================================================== + + /** + * DTO → Spring Security Authentication 변환 + * 여기서는 간단하게 "ROLE_{role값}" 형태로 Authority를 구성. + * ex) role = 1 → "ROLE_1" + * 실제 프로젝트에서 0/1/2 같은 값에 대한 의미 매핑이 명확하다면, + * 이 메서드 안의 매핑 로직만 교체해서 쓰면 됨. + */ + public Authentication toAuthentication(JwtUserClaimsDto dto) { + String principal = dto.getUserId(); + + List authorities = new ArrayList<>(); + if (dto.getRole() != null) { + String authority = "ROLE_" + dto.getRole(); + authorities.add(new SimpleGrantedAuthority(authority)); + } + + return new UsernamePasswordAuthenticationToken( + principal, + null, + authorities + ); + } + + /** + * 토큰 → Authentication 변환 (JWT 파싱 + DTO 변환까지 한 번에) + */ + public Authentication toAuthentication(String token) throws JwtException { + JwtUserClaimsDto dto = toUserClaimsDto(token); + return toAuthentication(dto); + } + + // ====================================================== + // 내부 고정 토큰 처리 + // ====================================================== + + /** + * 이 토큰 문자열이 "내부 고정 토큰"인지 여부 + */ + public boolean isInternalFixedToken(String rawToken) { + String fixed = properties.getInternalFixedToken(); + return fixed != null && !fixed.isBlank() && fixed.equals(rawToken); + } + + /** + * 내부 고정 토큰용 DTO 생성 + * - JwtProperties 에서 내부 시스템 계정을 정의해두고 사용 + */ + public JwtUserClaimsDto createInternalUserClaimsDto() { + return JwtUserClaimsDto.builder() + .userId(properties.getInternalUserId()) + .userTeam(properties.getInternalUserTeam()) + .userName(properties.getInternalUserName()) + .role(properties.getInternalUserRole()) + .build(); + } + + /** + * 내부 고정 토큰용 Authentication 생성 + */ + public Authentication createInternalAuthentication() { + JwtUserClaimsDto dto = createInternalUserClaimsDto(); + return toAuthentication(dto); + } +} \ No newline at end of file diff --git a/src/main/java/com/kri/common/auth/jwt/JwtUserClaimsDto.java b/src/main/java/com/kri/common/auth/jwt/JwtUserClaimsDto.java new file mode 100644 index 0000000..b03b4bf --- /dev/null +++ b/src/main/java/com/kri/common/auth/jwt/JwtUserClaimsDto.java @@ -0,0 +1,26 @@ +package com.kri.common.auth.jwt; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Builder; +import lombok.Value; + +@Schema( + name = "JwtUserClaimsDto", + description = "JWT에 포함되는 사용자 정보" +) +@Value +@Builder +public class JwtUserClaimsDto { + + @Schema(description = "사용자 ID (T_USER.USER_ID)") + String userId; + + @Schema(description = "팀 코드 또는 팀명 (T_USER.USER_TEAM)") + String userTeam; + + @Schema(description = "사용자 이름 (T_USER.USER_NM)") + String userName; + + @Schema(description = "권한 코드 (T_USER.ROLL, INTEGER)") + Integer role; +} diff --git a/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 05f3b22..54675c2 100644 --- a/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1,3 +1,4 @@ com.kri.common.web.CommonWebAutoConfiguration com.kri.common.redis.CommonRedisAutoConfiguration -com.kri.common.scheduling.CommonSchedulingAutoConfiguration \ No newline at end of file +com.kri.common.scheduling.CommonSchedulingAutoConfiguration +com.kri.common.auth.jwt.JwtAutoConfiguration