251114_01_ENH : JWT, API-Key 기능 추가, README 작성

This commit is contained in:
2025-11-14 12:17:18 +09:00
parent 4883eb7e20
commit 4bbcbedc7d
12 changed files with 1112 additions and 10 deletions

View 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);
}
}