251114_01_ENH : JWT, API-Key 기능 추가, README 작성
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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";
|
||||
}
|
||||
@@ -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<JwtUserClaimsDto> findUserByApiKey(String apiKey);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
62
src/main/java/com/kri/common/auth/jwt/JwtProperties.java
Normal file
62
src/main/java/com/kri/common/auth/jwt/JwtProperties.java
Normal file
@@ -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;
|
||||
}
|
||||
216
src/main/java/com/kri/common/auth/jwt/JwtService.java
Normal file
216
src/main/java/com/kri/common/auth/jwt/JwtService.java
Normal file
@@ -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<String, Object> 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<String, Object> buildClaims(JwtUserClaimsDto dto) {
|
||||
Map<String, Object> 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<String, Object> 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<Claims> 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<GrantedAuthority> 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);
|
||||
}
|
||||
}
|
||||
26
src/main/java/com/kri/common/auth/jwt/JwtUserClaimsDto.java
Normal file
26
src/main/java/com/kri/common/auth/jwt/JwtUserClaimsDto.java
Normal file
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user