261102_01_ENH: 요청 사용자 Context Provider 공용화 및 beta.1.7.1 버전 상향

This commit is contained in:
2026-11-02 13:59:34 +09:00
parent 59a4281cea
commit 2bbda10eb5
10 changed files with 116 additions and 49 deletions

View File

@@ -21,6 +21,7 @@ Source: .agent/consumer-references/platform-capabilities.md
- Common Web may register error handling, tracing/MDC, request-user resolution, enum conversion, and CORS behavior. Check for overlap before defining consumer-local equivalents.
- Swagger support requires springdoc and defines the shared Bearer/API-key schemes and grouped paths.
- When Swagger auto-configuration is active (`kri.swagger.enabled=true`, default), `RequestUserContext` controller arguments are ignored as request inputs globally, including their `authenticated`, `clientIp`, and `userRole` properties. Runtime argument resolution is unchanged.
- `RequestUserContextProvider` is a public injectable API for resolving the same request identity and client IP used by controller arguments. Its default registration requires Web integration and JwtService; a consumer provider overrides it. Existing principal/details/verified-Bearer fallback, empty-context behavior, resolver overrides and the JwtService resolver constructor remain unchanged. The provider does not enforce authentication or business authorization.
- Redis and scheduling are opt-in through their `kri.*.enabled` settings and matching runtime dependencies.
- HTTP bypass targets are server-configured. Never accept an arbitrary full target URL from a frontend; retain allowed-path checks and do not forward hop-by-hop headers.
- The external API client returns response bodies as documented, while bypass responses preserve raw bytes and target `Content-Type`.

View File

@@ -15,6 +15,7 @@
- Common Web may register error handling, tracing/MDC, request-user resolution, enum conversion, and CORS behavior. Check for overlap before defining consumer-local equivalents.
- Swagger support requires springdoc and defines the shared Bearer/API-key schemes and grouped paths.
- When Swagger auto-configuration is active (`kri.swagger.enabled=true`, default), `RequestUserContext` controller arguments are ignored as request inputs globally, including their `authenticated`, `clientIp`, and `userRole` properties. Runtime argument resolution is unchanged.
- `RequestUserContextProvider` is a public injectable API for resolving the same request identity and client IP used by controller arguments. Its default registration requires Web integration and JwtService; a consumer provider overrides it. Existing principal/details/verified-Bearer fallback, empty-context behavior, resolver overrides and the JwtService resolver constructor remain unchanged. The provider does not enforce authentication or business authorization.
- Redis and scheduling are opt-in through their `kri.*.enabled` settings and matching runtime dependencies.
- HTTP bypass targets are server-configured. Never accept an arbitrary full target URL from a frontend; retain allowed-path checks and do not forward hop-by-hop headers.
- The external API client returns response bodies as documented, while bypass responses preserve raw bytes and target `Content-Type`.

View File

@@ -6,6 +6,7 @@
- For HTTP/2 header safety and original upstream error propagation, use the shared HTTP/bypass features documented in the routed platform-capabilities reference instead of implementing consumer-local header filters and raw-response exception handlers.
- Response customizers may call `requireSuccess()`; its upstream exception propagates unchanged. Response charset parsing ignores charset-like text inside other quoted header parameters.
- When Swagger auto-configuration is active, `RequestUserContext` controller arguments are excluded from request input documentation; server-side authentication and client IP injection remain unchanged.
- `RequestUserContextProvider` is a public injectable API for resolving the same request identity and client IP used by controller arguments. Its default registration requires Web integration and JwtService; a consumer provider overrides it. Existing principal/details/verified-Bearer fallback, empty-context behavior, resolver overrides and the JwtService resolver constructor remain unchanged. The provider does not enforce authentication or business authorization.
- ExcelMapper's Path-based readStreaming and readHeaderStreaming use PackageAccess.READ, preserving source bytes, size, and modification time, including repeated reads and callback failures. Read-only files are supported, and file handles are released on success or failure; option validation, exception handling, and SAX streaming remain unchanged.
- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope.

View File

@@ -235,6 +235,7 @@ When implementation is complete, report in Korean:
- For HTTP/2 header safety and original upstream error propagation, use the shared HTTP/bypass features documented in the routed platform-capabilities reference instead of implementing consumer-local header filters and raw-response exception handlers.
- Response customizers may call `requireSuccess()`; its upstream exception propagates unchanged. Response charset parsing ignores charset-like text inside other quoted header parameters.
- When Swagger auto-configuration is active, `RequestUserContext` controller arguments are excluded from request input documentation; server-side authentication and client IP injection remain unchanged.
- `RequestUserContextProvider` is a public injectable API for resolving the same request identity and client IP used by controller arguments. Its default registration requires Web integration and JwtService; a consumer provider overrides it. Existing principal/details/verified-Bearer fallback, empty-context behavior, resolver overrides and the JwtService resolver constructor remain unchanged. The provider does not enforce authentication or business authorization.
- ExcelMapper's Path-based readStreaming and readHeaderStreaming use PackageAccess.READ, preserving source bytes, size, and modification time, including repeated reads and callback failures. Read-only files are supported, and file handles are released on success or failure; option validation, exception handling, and SAX streaming remain unchanged.
- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope.

View File

@@ -99,6 +99,20 @@ import com.kri.common.feature.web.RequestUserContext;
컨트롤러 파라미터로 선언하면 현재 인증 사용자와 client IP를 받을 수 있습니다. `JwtService` Bean이 있을 때 `RequestUserContextArgumentResolver`가 자동 등록됩니다.
`beta.1.7.1`부터 인터셉터 등에서도 공개 API인 `RequestUserContextProvider`를 주입받아 동일한 컨텍스트를 조회할 수 있습니다.
```java
import com.kri.common.feature.web.RequestUserContext;
import com.kri.common.feature.web.RequestUserContextProvider;
// 생성자로 주입받은 Provider를 요청 처리 중 호출합니다.
RequestUserContext ctx = requestUserContextProvider.resolve(request);
```
기본 Provider는 기존 Resolver의 principal → details → 검증된 Bearer 토큰 순서와 IP 해석을 유지합니다. 인증 정보를 찾지 못하면 사용자 필드가 비어 있는 컨텍스트를 반환합니다. 요청 파라미터에서 사용자 정보를 가져오지 않으며, 인증 필수 여부나 업무 권한은 호출 서비스에서 검사해야 합니다. 요청 간 컨텍스트를 캐시하지 않습니다.
기본 Provider는 `kri.web.enabled=true`와 `JwtService` Bean이 있을 때 등록되며, 서비스가 `RequestUserContextProvider` Bean을 제공하면 이를 사용합니다. 기존 컨트롤러 주입 방식과 Resolver 교체 지점, `JwtService`를 받는 기존 Resolver 생성자는 유지됩니다. Provider도 기존 Web 통합과 마찬가지로 Servlet/Spring Web classpath가 필요합니다.
Swagger 자동 구성이 활성화되면 `RequestUserContext`는 요청 입력 문서에서 제외됩니다. `authenticated`, `clientIp`, `userRole` 등의 입력 항목은 표시되지 않으며, 실제 요청의 인증 정보와 IP 주입 동작은 유지됩니다.
```java
@@ -932,6 +946,8 @@ Endpoint:
## 변경 이력
- 2026-11-02: `beta.1.7.1`에서 공개 `RequestUserContextProvider`를 추가하고 기존 컨트롤러 인자 해석을 위임하도록 정리했습니다. 인증 정보와 IP 해석, 기존 Resolver 생성자 및 자동 등록 조건을 유지합니다.
- 2026-08-06: `beta.1.6.3`에서 non-ASCII multipart 파일명을 ASCII fallback/
`filename*` 없이 원본 `filename`의 UTF-8 바이트로 전송하도록 복원했습니다.
- 2026-08-06: `beta.1.6.2`에서 non-ASCII multipart 파일명에 ASCII `filename`

View File

@@ -4,7 +4,7 @@ plugins {
}
// 버전 변경은 여기서
def commonVer = "beta.1.7.0"
def commonVer = "beta.1.7.1"
group = 'com.kri.common'
version = commonVer

View File

@@ -1,6 +1,8 @@
package com.kri.common.autoconfigure.web;
import com.kri.common.feature.auth.jwt.JwtService;
import com.kri.common.feature.web.RequestUserContextProvider;
import com.kri.common.runtime.web.DefaultRequestUserContextProvider;
import com.kri.common.runtime.web.CodeEnumConverter;
import com.kri.common.runtime.web.ErrorAdvice;
import com.kri.common.runtime.web.ServiceMdcAspect;
@@ -78,13 +80,21 @@ public class CommonWebAutoConfiguration {
};
}
@Bean
@ConditionalOnClass(HttpServletRequest.class)
@ConditionalOnBean(JwtService.class)
@ConditionalOnMissingBean(RequestUserContextProvider.class)
public RequestUserContextProvider requestUserContextProvider(JwtService jwtService) {
return new DefaultRequestUserContextProvider(jwtService);
}
@Bean
@ConditionalOnBean(JwtService.class)
@ConditionalOnMissingBean
public RequestUserContextArgumentResolver requestUserContextArgumentResolver(
JwtService jwtService
RequestUserContextProvider requestUserContextProvider
) {
return new RequestUserContextArgumentResolver(jwtService);
return new RequestUserContextArgumentResolver(requestUserContextProvider);
}
@Bean

View File

@@ -0,0 +1,11 @@
package com.kri.common.feature.web;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.lang.Nullable;
/** Provides the same user context used by controller argument resolution. */
public interface RequestUserContextProvider {
/** Resolves existing authentication or a verified Bearer token; otherwise returns an empty context. */
RequestUserContext resolve(@Nullable HttpServletRequest request);
}

View File

@@ -0,0 +1,60 @@
package com.kri.common.runtime.web;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
import com.kri.common.feature.auth.jwt.JwtService;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.common.feature.web.RequestUserContextProvider;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
@RequiredArgsConstructor
public class DefaultRequestUserContextProvider implements RequestUserContextProvider {
private final JwtService jwtService;
@Override
public RequestUserContext resolve(@Nullable HttpServletRequest request) {
String clientIp = request != null ? IpUtil.getClientIp(request) : null;
JwtUserClaimsDto claims = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof JwtUserClaimsDto jwtDto) {
claims = jwtDto;
} else {
Object details = auth.getDetails();
if (details instanceof JwtUserClaimsDto jwtDto) {
claims = jwtDto;
}
}
}
if (claims == null && request != null) {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
try {
claims = jwtService.toUserClaimsDto(authHeader.substring(7));
} catch (JwtException ignored) {
}
}
}
if (claims == null) {
return RequestUserContext.builder().clientIp(clientIp).build();
}
return RequestUserContext.builder()
.userId(claims.getUserId())
.userCmpn(claims.getUserCmpn())
.userTeam(claims.getUserTeam())
.userName(claims.getUserName())
.userRole(claims.getUserRole())
.clientIp(clientIp)
.build();
}
}

View File

@@ -1,24 +1,27 @@
package com.kri.common.runtime.web;
import com.kri.common.feature.auth.dto.JwtUserClaimsDto;
import com.kri.common.feature.auth.jwt.JwtService;
import com.kri.common.feature.web.RequestUserContext;
import io.jsonwebtoken.JwtException;
import com.kri.common.feature.web.RequestUserContextProvider;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@RequiredArgsConstructor
public class RequestUserContextArgumentResolver implements HandlerMethodArgumentResolver {
private final JwtService jwtService;
private final RequestUserContextProvider requestUserContextProvider;
public RequestUserContextArgumentResolver(JwtService jwtService) {
this(new DefaultRequestUserContextProvider(jwtService));
}
public RequestUserContextArgumentResolver(RequestUserContextProvider requestUserContextProvider) {
this.requestUserContextProvider = requestUserContextProvider;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
@@ -32,44 +35,7 @@ public class RequestUserContextArgumentResolver implements HandlerMethodArgument
NativeWebRequest webRequest,
@Nullable WebDataBinderFactory binderFactory
) {
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
String clientIp = request != null ? IpUtil.getClientIp(request) : null;
JwtUserClaimsDto claims = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof JwtUserClaimsDto jwtDto) {
claims = jwtDto;
} else {
Object details = auth.getDetails();
if (details instanceof JwtUserClaimsDto jwtDto) {
claims = jwtDto;
}
}
}
if (claims == null && request != null) {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
try {
claims = jwtService.toUserClaimsDto(authHeader.substring(7));
} catch (JwtException ignored) {
}
}
}
if (claims == null) {
return RequestUserContext.builder().clientIp(clientIp).build();
}
return RequestUserContext.builder()
.userId(claims.getUserId())
.userCmpn(claims.getUserCmpn())
.userTeam(claims.getUserTeam())
.userName(claims.getUserName())
.userRole(claims.getUserRole())
.clientIp(clientIp)
.build();
return requestUserContextProvider.resolve(
webRequest.getNativeRequest(HttpServletRequest.class));
}
}