260212_01_DOC: 프로젝트 전체에 구글 java 스타일 적용
This commit is contained in:
89
README.md
89
README.md
@@ -20,6 +20,7 @@ Spring Boot 기반 사내 서비스에서 공통으로 사용하는 기능들을
|
||||
- 주요 클래스: `ExternalApiClient`, `ExternalApiResponse`
|
||||
|
||||
지원 메서드(문자열 body 기반)
|
||||
|
||||
- `ExternalApiResponse get(String url, Map<String,String> headers)`
|
||||
- `ExternalApiResponse post(String url, Map<String,String> headers, String body)`
|
||||
- `ExternalApiResponse put(String url, Map<String,String> headers, String body)`
|
||||
@@ -27,11 +28,13 @@ Spring Boot 기반 사내 서비스에서 공통으로 사용하는 기능들을
|
||||
- `ExternalApiResponse delete(String url, Map<String,String> headers)`
|
||||
|
||||
기본 동작
|
||||
|
||||
- 연결 타임아웃: 10초, 요청 타임아웃: 30초
|
||||
- body가 있고 `Content-Type` 헤더가 없으면 자동으로 `application/json; charset=utf-8` 설정
|
||||
- 예외 발생 시 `RuntimeException`으로 래핑하여 전달하며, `InterruptedException` 발생 시 인터럽트 플래그를 복원
|
||||
|
||||
응답 객체(`ExternalApiResponse`)
|
||||
|
||||
- 필드: `statusCode`(int), `headers`(Map<String, List<String>>), `body`(String)
|
||||
- 정적 팩토리: `ExternalApiResponse.of(int, HttpHeaders, String)`
|
||||
|
||||
@@ -77,6 +80,7 @@ ExternalApiClient client = new ExternalApiClient(httpClient, Duration.ofSeconds(
|
||||
```
|
||||
|
||||
주의사항
|
||||
|
||||
- 메서드 시그니처는 문자열 기반 body를 사용하므로, JSON 외 포맷을 전송할 경우 적절한 `Content-Type`을 직접 지정하세요.
|
||||
- 대용량 응답이 예상된다면 현재 구현은 `BodyHandlers.ofString()`을 사용한다는 점에 유의하세요.
|
||||
|
||||
@@ -264,6 +268,7 @@ kri:
|
||||
- com.kri.common.scheduling: 스케줄링 자동 활성화 (선택 사용)
|
||||
|
||||
권장 의존 방향(순환 금지):
|
||||
|
||||
- auth.jwt, auth.apikey → 다른 모듈에 의존하지 않음(핵심 도메인 유틸)
|
||||
- security → auth.* 에 의존(필터 순서/체인 구성)
|
||||
- web, webmvc → spring-web 중심, security에 의존하지 않음
|
||||
@@ -272,25 +277,33 @@ kri:
|
||||
|
||||
### 0.2 AutoConfiguration 로딩과 오버라이드 전략
|
||||
|
||||
자동 구성은 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports로 등록되며, 다음 순서/특징을 가집니다.
|
||||
자동 구성은 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports로 등록되며, 다음
|
||||
순서/특징을 가집니다.
|
||||
|
||||
1) com.kri.common.auth.jwt.JwtAutoConfiguration
|
||||
|
||||
- JwtProperties 바인딩, JwtService, ApiKeyAuthFilter 등 기초 컴포넌트 제공
|
||||
|
||||
2) com.kri.common.security.KriSecurityAutoConfiguration
|
||||
|
||||
- SecurityFilterChain 기본 구성, @EnableMethodSecurity 활성화, 필터 체인에 ApiKey → JWT 순서로 필터 삽입
|
||||
- before = SecurityAutoConfiguration 으로 Spring 기본 보안 자동구성보다 먼저 개입
|
||||
|
||||
3) com.kri.common.web.CommonWebAutoConfiguration, com.kri.common.webmvc.KriWebMvcAutoConfiguration
|
||||
|
||||
- 공통 예외/로깅, CORS, Swagger 접근 IP 제어 인터셉터
|
||||
|
||||
4) com.kri.common.swagger.KriSwaggerAutoConfiguration
|
||||
|
||||
- OpenAPI/Swagger 설정, Bearer/JWT + API Key SecurityScheme 등록
|
||||
|
||||
5) com.kri.common.redis.CommonRedisAutoConfiguration, com.kri.common.scheduling.CommonSchedulingAutoConfiguration
|
||||
5) com.kri.common.redis.CommonRedisAutoConfiguration,
|
||||
com.kri.common.scheduling.CommonSchedulingAutoConfiguration
|
||||
|
||||
- 선택 기능: RedisQueueHelper, @EnableScheduling
|
||||
|
||||
오버라이드 규칙:
|
||||
|
||||
- 동일 타입의 Bean을 서비스에서 정의하면 @ConditionalOnMissingBean에 의해 서비스 정의가 우선
|
||||
- 프로퍼티로 on/off 토글(@ConditionalOnProperty)
|
||||
|
||||
@@ -299,7 +312,7 @@ kri:
|
||||
- Stateless 세션, CSRF 비활성화, CORS 기본 허용
|
||||
- public-paths는 permitAll, 그 외 anyRequest().authenticated()
|
||||
- 필터 순서: ApiKeyAuthFilter → JwtAuthenticationFilter → UsernamePasswordAuthenticationFilter
|
||||
- 외부/파트너용 API Key가 있다면 먼저 인증 세팅, 없으면 Bearer JWT 처리
|
||||
- 외부/파트너용 API Key가 있다면 먼저 인증 세팅, 없으면 Bearer JWT 처리
|
||||
|
||||
### 0.4 설정 네임스페이스 정리
|
||||
|
||||
@@ -389,7 +402,7 @@ KriCommon은 다음 AutoConfiguration 들을 제공합니다.
|
||||
모두 `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`에서 자동 등록됩니다.
|
||||
|
||||
| 클래스 | 역할 요약 |
|
||||
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
|
||||
|---------------------------------------------------------------|---------------------------------------------------------------------------------------|
|
||||
| `com.kri.common.auth.jwt.JwtAutoConfiguration` | `JwtProperties`, `ApiKeyProperties` 바인딩 + `JwtService`, `ApiKeyAuthFilter` 자동 Bean 생성 |
|
||||
| `com.kri.common.security.KriSecurityAutoConfiguration` | SecurityFilterChain 기본 구성(JWT + API Key 필터) + `@EnableMethodSecurity` |
|
||||
| `com.kri.common.web.CommonWebAutoConfiguration` | 공통 예외 처리(`ErrorAdvice`), `TraceFilter` 등록 |
|
||||
@@ -499,7 +512,7 @@ public class JwtProperties {
|
||||
**프로퍼티 요약**
|
||||
|
||||
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
||||
| --------------------------------------------- | ------ | ------------ | -------------------------------------- |
|
||||
|-----------------------------------------------|--------|--------------|----------------------------------------|
|
||||
| `kri.auth.jwt.secret` | String | (기본값 있음) | HMAC 서명용 시크릿(최소 32자 이상, 서비스별로 꼭 변경 추천) |
|
||||
| `kri.auth.jwt.issuer` | String | `kri-it` | 토큰 발급자 |
|
||||
| `kri.auth.jwt.access-token-validity-seconds` | long | 86,400 (24h) | Access Token 만료(초) |
|
||||
@@ -600,7 +613,7 @@ public class ApiKeyProperties {
|
||||
**프로퍼티 요약**
|
||||
|
||||
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
||||
| ----------------------------- | ------- | ----------- | ----------------------- |
|
||||
|-------------------------------|---------|-------------|-------------------------|
|
||||
| `kri.auth.apikey.enabled` | boolean | `false` | API Key 인증 기능 사용 여부 |
|
||||
| `kri.auth.apikey.header-name` | String | `X-API-Key` | API Key 를 읽을 HTTP 헤더 이름 |
|
||||
|
||||
@@ -677,7 +690,7 @@ public class KriSecurityProperties {
|
||||
**프로퍼티 요약**
|
||||
|
||||
| 프로퍼티 | 타입 | 기본값 (일부) | 설명 |
|
||||
| --------------------------- | ------------ | ---------------- | -------------------------- |
|
||||
|-----------------------------|--------------|------------------|----------------------------|
|
||||
| `kri.security.enabled` | boolean | `true` | 공통 Security 자동 구성 사용 여부 |
|
||||
| `kri.security.public-paths` | List<String> | Swagger 관련 패턴 포함 | `permitAll()` 로 열어둘 URL 목록 |
|
||||
|
||||
@@ -866,7 +879,7 @@ public class KriIpAccessProperties {
|
||||
**프로퍼티 요약**
|
||||
|
||||
| 프로퍼티 | 타입 | 설명 |
|
||||
| -------------------------------- | ------------ | --------------------------------- |
|
||||
|----------------------------------|--------------|-----------------------------------|
|
||||
| `kri.webmvc.enabled` | boolean | CORS 및 Swagger IP 제어 자동 구성 on/off |
|
||||
| `kri.webmvc.ip.additional-cidrs` | List<String> | 기본 CIDR 목록에 *추가*할 CIDR 리스트 |
|
||||
|
||||
@@ -944,7 +957,7 @@ public class CommonRedisAutoConfiguration {
|
||||
**프로퍼티**
|
||||
|
||||
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
||||
| ---------------------- | ------- | ----- | ---------------------- |
|
||||
|------------------------|---------|-------|------------------------|
|
||||
| `common.redis.enabled` | boolean | false | RedisQueueHelper 사용 여부 |
|
||||
|
||||
#### 4.6.2. RedisQueueHelper 사용 예시
|
||||
@@ -980,7 +993,7 @@ public class CommonSchedulingAutoConfiguration { }
|
||||
**프로퍼티**
|
||||
|
||||
| 프로퍼티 | 타입 | 기본값 | 설명 |
|
||||
| --------------------------- | ------- | ----- | -------------------------- |
|
||||
|-----------------------------|---------|-------|----------------------------|
|
||||
| `common.scheduling.enabled` | boolean | false | `@EnableScheduling` 활성화 여부 |
|
||||
|
||||
서비스 쪽에서는 단순히:
|
||||
@@ -1022,7 +1035,6 @@ common:
|
||||
|
||||
**던지기만 하면** `ErrorAdvice`가 잡아서 `ProblemDetail` 포맷으로 응답을 내려줍니다.
|
||||
|
||||
|
||||
#### 4.9.2. 기본 사용 패턴
|
||||
|
||||
* 4.9.2.1. Not Found (404)
|
||||
@@ -1040,12 +1052,14 @@ public User getUserOrThrow(String userId) {
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
- HTTP 상태: 404
|
||||
- code: "USER_NOT_FOUND"
|
||||
- message: "해당 사용자를 찾을 수 없습니다."
|
||||
- extras: { "userId": "..." }
|
||||
|
||||
* 4.9.2.2. Conflict (409)
|
||||
|
||||
```
|
||||
if (userRepository.existsByLoginId(loginId)) {
|
||||
throw BusinessException.conflict(
|
||||
@@ -1056,6 +1070,7 @@ if (userRepository.existsByLoginId(loginId)) {
|
||||
```
|
||||
|
||||
* 4.9.2.3. Forbidden (403)
|
||||
|
||||
```
|
||||
if (!currentUser.canAccess(targetProject)) {
|
||||
throw BusinessException.forbidden(
|
||||
@@ -1066,7 +1081,9 @@ if (!currentUser.canAccess(targetProject)) {
|
||||
```
|
||||
|
||||
#### 4.9.3. 임의 상태 코드 지정: of(...)
|
||||
|
||||
of(HttpStatus status, String code, String message) 팩토리로 원하는 상태 코드를 직접 지정할 수 있습니다.
|
||||
|
||||
```
|
||||
throw BusinessException.of(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
@@ -1075,7 +1092,9 @@ throw BusinessException.of(
|
||||
).with("param", "startDate");
|
||||
|
||||
```
|
||||
|
||||
추가 정보를 한 번에 넘기고 싶으면:
|
||||
|
||||
```
|
||||
Map<String, Object> extras = Map.of(
|
||||
"param", "startDate",
|
||||
@@ -1089,21 +1108,27 @@ throw BusinessException.of(
|
||||
extras
|
||||
);
|
||||
```
|
||||
|
||||
> 실제 구현에는 of(status, code, message, Map<String,Object>) 시그니처가 존재합니다.
|
||||
|
||||
#### 4.9.4. extras 체이닝: with(...) 활용
|
||||
|
||||
with(key, value)는 새로운 예외 인스턴스를 리턴하는 체이닝 메서드입니다.
|
||||
|
||||
```
|
||||
throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
|
||||
.with("userId", userId)
|
||||
.with("searchType", "INTRANET");
|
||||
```
|
||||
|
||||
* 내부적으로 extras를 복사해 새 인스턴스를 만드는 방식이라, immutable 스타일로 안전하게 체이닝할 수 있습니다.
|
||||
|
||||
#### 4.9.5. Service / Controller에서의 사용 위치
|
||||
|
||||
Service에서 던지고, Controller는 깔끔하게 유지
|
||||
|
||||
Service 예시
|
||||
Service 예시
|
||||
|
||||
```
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -1124,6 +1149,7 @@ public class UserService {
|
||||
```
|
||||
|
||||
Controller 예시
|
||||
|
||||
```
|
||||
@RestController
|
||||
@RequestMapping("/api/users")
|
||||
@@ -1145,12 +1171,15 @@ public class UserController {
|
||||
* ErrorAdvice가 @ExceptionHandler(BusinessException.class)로 처리
|
||||
|
||||
#### 4.9.6. 실제 응답 JSON 예시
|
||||
|
||||
```
|
||||
throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
|
||||
.with("userId", "u-123");
|
||||
|
||||
```
|
||||
|
||||
요청 URL이 /api/users/u-123인 경우, 응답은 대략 다음과 같은 형태입니다.
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "about:blank",
|
||||
@@ -1166,6 +1195,7 @@ throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없
|
||||
"userId": "u-123"
|
||||
}
|
||||
```
|
||||
|
||||
> 이 포맷은 ErrorAdvice에서 공통으로 생성합니다.
|
||||
|
||||
#### 4.9.7. 로그 출력 정책
|
||||
@@ -1187,6 +1217,7 @@ ErrorAdvice 내부 로깅 정책(요약):
|
||||
#### 4.9.8. 에러 코드 enum으로 관리하기 (선택)
|
||||
|
||||
서비스에서 에러 코드를 enum으로 관리하면 나중에 유지보수가 쉬워집니다.
|
||||
|
||||
```
|
||||
public enum UserErrorCodes {
|
||||
USER_NOT_FOUND,
|
||||
@@ -1199,6 +1230,7 @@ throw BusinessException.notFound(
|
||||
"사용자를 찾을 수 없습니다."
|
||||
).with("userId", userId);
|
||||
```
|
||||
|
||||
#### 4.9.9. 요약
|
||||
|
||||
1. 던지는 쪽 (Service)
|
||||
@@ -1208,13 +1240,14 @@ throw BusinessException.notFound(
|
||||
* 필요시 of(status, code, message)
|
||||
* with("key", value)로 추가 정보(extras) 세팅
|
||||
2. 받는 쪽 (Controller)
|
||||
* 별도 try/catch 필요 없음
|
||||
* ErrorAdvice가 자동으로 JSON + 로그 처리
|
||||
* 별도 try/catch 필요 없음
|
||||
* ErrorAdvice가 자동으로 JSON + 로그 처리
|
||||
3. 클라이언트/FE 입장
|
||||
* 응답은 ProblemDetail 포맷 + code + extras 일관 구조
|
||||
* FE에서는 code 기준으로 에러 분기 처리하면 됨
|
||||
|
||||
---
|
||||
|
||||
## 5. example-service 적용 요약
|
||||
|
||||
1. **의존성 추가**
|
||||
@@ -1263,34 +1296,38 @@ throw BusinessException.notFound(
|
||||
## 7. 문제 해결 가이드(Troubleshooting)
|
||||
|
||||
- 애플리케이션 시작 시 "kri.auth.jwt.secret must be at least 32 bytes" 오류
|
||||
- 원인: JWT 시크릿 최소 길이 미달
|
||||
- 조치: application.yml의 `kri.auth.jwt.secret`를 UTF-8 32바이트 이상 난수로 교체
|
||||
- 원인: JWT 시크릿 최소 길이 미달
|
||||
- 조치: application.yml의 `kri.auth.jwt.secret`를 UTF-8 32바이트 이상 난수로 교체
|
||||
|
||||
- 모든 요청이 401 Unauthorized
|
||||
- 원인1: Authorization 헤더에 Bearer 토큰 미포함
|
||||
- 원인2: 토큰 만료/서명 불일치(issuer 불일치 포함)
|
||||
- 조치: 로그인 API로 토큰 재발급, issuer와 secret 확인, 클럭 드리프트 점검
|
||||
- 원인1: Authorization 헤더에 Bearer 토큰 미포함
|
||||
- 원인2: 토큰 만료/서명 불일치(issuer 불일치 포함)
|
||||
- 조치: 로그인 API로 토큰 재발급, issuer와 secret 확인, 클럭 드리프트 점검
|
||||
|
||||
- Swagger 페이지가 접근 불가(403/404)
|
||||
- 원인: IP 접근 제어 또는 public-paths 미설정
|
||||
- 조치: `kri.webmvc.ip.additional-cidrs`에 현재 IP 대역 추가 또는 `kri.security.public-paths`에 Swagger 경로 포함
|
||||
- 원인: IP 접근 제어 또는 public-paths 미설정
|
||||
- 조치: `kri.webmvc.ip.additional-cidrs`에 현재 IP 대역 추가 또는 `kri.security.public-paths`에 Swagger 경로
|
||||
포함
|
||||
|
||||
- ApiKeyUserClaimsProvider가 동작하지 않음
|
||||
- 원인: Bean 미등록 또는 `kri.auth.apikey.enabled=false`
|
||||
- 조치: 구현체 @Component 등록, 프로퍼티 enabled=true 설정, 헤더 이름 일치 여부 점검
|
||||
- 원인: Bean 미등록 또는 `kri.auth.apikey.enabled=false`
|
||||
- 조치: 구현체 @Component 등록, 프로퍼티 enabled=true 설정, 헤더 이름 일치 여부 점검
|
||||
|
||||
---
|
||||
|
||||
## 8. FAQ
|
||||
|
||||
- Q. API Key와 JWT는 어떻게 같이 쓰나요?
|
||||
- A. 필터 체인에서 API Key가 먼저 검사되어 인증을 세팅하고, 없거나 실패하면 JWT가 검사됩니다. 외부 파트너는 API Key, 내부/사용자 트래픽은 JWT를 권장합니다.
|
||||
- A. 필터 체인에서 API Key가 먼저 검사되어 인증을 세팅하고, 없거나 실패하면 JWT가 검사됩니다. 외부 파트너는 API Key, 내부/사용자 트래픽은 JWT를
|
||||
권장합니다.
|
||||
|
||||
- Q. ROLE 매핑은 어디서 바꾸나요?
|
||||
- A. JwtService.toAuthentication(JwtUserClaimsDto) 내부에서 "ROLE_{숫자}"로 생성합니다. 서비스 정책에 맞게 해당 메서드를 오버라이드하거나 래핑하십시오.
|
||||
- A. JwtService.toAuthentication(JwtUserClaimsDto) 내부에서 "ROLE_{숫자}"로 생성합니다. 서비스 정책에 맞게 해당 메서드를
|
||||
오버라이드하거나 래핑하십시오.
|
||||
|
||||
- Q. 기본 Security를 전면 교체할 수 있나요?
|
||||
- A. 서비스에서 SecurityFilterChain Bean을 직접 정의하면, `@ConditionalOnMissingBean` 규칙에 의해 서비스 정의가 우선 적용됩니다.
|
||||
- A. 서비스에서 SecurityFilterChain Bean을 직접 정의하면, `@ConditionalOnMissingBean` 규칙에 의해 서비스 정의가 우선
|
||||
적용됩니다.
|
||||
|
||||
---
|
||||
|
||||
|
||||
Reference in New Issue
Block a user