251218_01_ENH : API-KEY DB적재 및 로컬 캐싱 기능 추가
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
package com.kri.common.auth.apikey;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
@AutoConfiguration
|
||||
@ConditionalOnClass(ApiKeyAdminController.class)
|
||||
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "admin-api-enabled", havingValue = "true")
|
||||
@Import(ApiKeyAdminController.class) // ✅ 컴포넌트 스캔 없이도 Bean 등록
|
||||
public class ApiKeyAdminAutoConfiguration {
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.kri.common.auth.apikey;
|
||||
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.web.util.matcher.IpAddressMatcher;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/internal/apikey")
|
||||
@ConditionalOnProperty(prefix="kri.auth.apikey", name="admin-api-enabled", havingValue="true")
|
||||
public class ApiKeyAdminController {
|
||||
private final ApiKeyProperties props;
|
||||
private final PreloadedApiKeyUserClaimsProvider provider;
|
||||
private final List<IpAddressMatcher> allow;
|
||||
|
||||
public ApiKeyAdminController(ApiKeyProperties props, PreloadedApiKeyUserClaimsProvider provider) {
|
||||
this.props = props;
|
||||
this.provider = provider;
|
||||
this.allow = props.getAdminAllowIps().stream().map(IpAddressMatcher::new).toList();
|
||||
}
|
||||
|
||||
@PostMapping("/reload")
|
||||
public ReloadResult reload(HttpServletRequest req) {
|
||||
assertAllowed(req);
|
||||
int count = provider.reloadFromDb();
|
||||
return new ReloadResult(count);
|
||||
}
|
||||
|
||||
/** 현재 캐시 상태(키는 마스킹) */
|
||||
@GetMapping("/cache")
|
||||
public List<CachedKeyView> cache(HttpServletRequest req) {
|
||||
assertAllowed(req);
|
||||
Map<String, JwtUserClaimsDto> snap = provider.snapshot();
|
||||
return snap.entrySet().stream()
|
||||
.map(e -> new CachedKeyView(mask(e.getKey()), e.getValue()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private void assertAllowed(HttpServletRequest req) {
|
||||
if (!props.isAdminApiEnabled()) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||
String remote = req.getRemoteAddr();
|
||||
boolean ok = allow.stream().anyMatch(m -> m.matches(remote));
|
||||
if (!ok) throw new ResponseStatusException(HttpStatus.FORBIDDEN, "IP not allowed: " + remote);
|
||||
}
|
||||
|
||||
private String mask(String raw) {
|
||||
if (raw == null) return "";
|
||||
int n = raw.length();
|
||||
if (n <= 8) return raw.charAt(0) + "****";
|
||||
return raw.substring(0, 4) + "****" + raw.substring(n - 4);
|
||||
}
|
||||
|
||||
public record ReloadResult(int cachedKeyCount) {}
|
||||
public record CachedKeyView(String maskedApiKey, JwtUserClaimsDto claims) {}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.kri.common.auth.apikey;
|
||||
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/*
|
||||
* @Primary 절대 금지
|
||||
* 메인 JPA와 완전히 분리
|
||||
*/
|
||||
@AutoConfiguration(
|
||||
afterName = {
|
||||
// 메인 JPA가 있는 서비스에서는 메인 auto-config 이후에 올라와도 되고,
|
||||
// 메인 JPA를 exclude한 서비스에서는 afterName이 무시되어도 동작해야 함.
|
||||
"org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration",
|
||||
"org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration"
|
||||
}
|
||||
)
|
||||
@ConditionalOnClass(name = {
|
||||
"org.springframework.data.jpa.repository.JpaRepository",
|
||||
"jakarta.persistence.EntityManagerFactory",
|
||||
"com.zaxxer.hikari.HikariDataSource"
|
||||
})
|
||||
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true")
|
||||
@EnableJpaRepositories(
|
||||
basePackages = "com.kri.common.auth.persistence.repository",
|
||||
entityManagerFactoryRef = "apiKeyEntityManagerFactory",
|
||||
transactionManagerRef = "apiKeyTransactionManager"
|
||||
)
|
||||
@EnableConfigurationProperties(ApiKeyProperties.class)
|
||||
public class ApiKeyJpaAutoConfiguration {
|
||||
|
||||
@Bean(name = "apiKeyDataSource")
|
||||
public DataSource apiKeyDataSource(ApiKeyProperties props) {
|
||||
var db = props.getDb();
|
||||
HikariDataSource ds = new HikariDataSource();
|
||||
ds.setJdbcUrl(db.getUrl());
|
||||
ds.setUsername(db.getUsername());
|
||||
ds.setPassword(db.getPassword());
|
||||
ds.setDriverClassName(db.getDriverClassName());
|
||||
return ds;
|
||||
}
|
||||
/**
|
||||
* ✅ EntityManagerFactoryBuilder에 의존하지 않는 방식
|
||||
* - intranet-extension처럼 HibernateJpaAutoConfiguration을 exclude 해도 동작
|
||||
*/
|
||||
@Bean(name = "apiKeyEntityManagerFactory")
|
||||
public LocalContainerEntityManagerFactoryBean apiKeyEntityManagerFactory(
|
||||
@Qualifier("apiKeyDataSource") DataSource ds,
|
||||
ObjectProvider<PersistenceUnitManager> pumProvider,
|
||||
ApiKeyProperties props
|
||||
) {
|
||||
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
vendorAdapter.setShowSql(props.getJpa().isShowSql());
|
||||
vendorAdapter.setGenerateDdl(false);
|
||||
|
||||
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
|
||||
emf.setDataSource(ds);
|
||||
emf.setJpaVendorAdapter(vendorAdapter);
|
||||
emf.setPackagesToScan("com.kri.common.auth.persistence.entity");
|
||||
emf.setPersistenceUnitName("apikey");
|
||||
|
||||
PersistenceUnitManager pum = pumProvider.getIfAvailable();
|
||||
if (pum != null) {
|
||||
emf.setPersistenceUnitManager(pum);
|
||||
}
|
||||
|
||||
// 최소 JPA 속성들 (원하면 yml로 확장 가능)
|
||||
Map<String, Object> jpaProps = new HashMap<>();
|
||||
jpaProps.put("hibernate.show_sql", Boolean.toString(props.getJpa().isShowSql()));
|
||||
jpaProps.put("hibernate.format_sql", Boolean.toString(props.getJpa().isFormatSql()));
|
||||
|
||||
emf.setJpaPropertyMap(jpaProps);
|
||||
return emf;
|
||||
}
|
||||
|
||||
@Bean(name = "apiKeyTransactionManager")
|
||||
public PlatformTransactionManager apiKeyTransactionManager(
|
||||
@Qualifier("apiKeyEntityManagerFactory") EntityManagerFactory emf
|
||||
) {
|
||||
return new JpaTransactionManager(emf);
|
||||
}
|
||||
|
||||
/**
|
||||
* ✅ intranet-extension처럼 메인 JPA auto-config를 exclude해서
|
||||
* 'jpaMappingContext'가 없을 때만 보완해준다.
|
||||
*
|
||||
* 메인 JPA가 있는 서비스에서는 이미 jpaMappingContext가 있으므로 이 빈은 생성되지 않아 영향이 없다.
|
||||
*/
|
||||
@Bean(name = "jpaMappingContext")
|
||||
@ConditionalOnMissingBean(name = "jpaMappingContext")
|
||||
public JpaMetamodelMappingContextFactoryBean jpaMappingContext(ApplicationContext ctx) {
|
||||
// FactoryBean으로 등록하면 내부에서 EntityManagerFactory들을 찾아 Metamodel을 구성함
|
||||
return new JpaMetamodelMappingContextFactoryBean();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.kri.common.auth.apikey;
|
||||
|
||||
import com.kri.common.auth.persistence.repository.ApiKeyRepository;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
@AutoConfiguration
|
||||
@EnableConfigurationProperties(ApiKeyProperties.class)
|
||||
@ConditionalOnProperty(prefix = "kri.auth.apikey", name = "enabled", havingValue = "true")
|
||||
public class ApiKeyPreloadAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(ApiKeyRepository.class) // ✅ apikey JPA 컨텍스트가 repo를 만들었을 때만
|
||||
@ConditionalOnMissingBean(ApiKeyUserClaimsProvider.class)
|
||||
public PreloadedApiKeyUserClaimsProvider apiKeyUserClaimsProvider(
|
||||
ApiKeyProperties props,
|
||||
ApiKeyRepository repo
|
||||
) {
|
||||
return new PreloadedApiKeyUserClaimsProvider(props, repo);
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,15 @@ import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "kri.auth.apikey")
|
||||
public class ApiKeyProperties {
|
||||
|
||||
/**
|
||||
* API Key 인증 사용 여부
|
||||
* API Key 인증 허용 여부
|
||||
*/
|
||||
private boolean enabled = false;
|
||||
|
||||
@@ -19,4 +21,42 @@ public class ApiKeyProperties {
|
||||
* 예: X-API-Key, X-EXTERNAL-KEY 등
|
||||
*/
|
||||
private String headerName = "X-API-Key";
|
||||
|
||||
/** 이 서비스의 코드 (서비스별 preload 범위 결정) */
|
||||
private String serviceCode;
|
||||
|
||||
/** 기동 시 preload 할지 */
|
||||
private boolean preloadOnStartup = false;
|
||||
|
||||
/** 내부 관리 API(리로드/조회) 노출 여부 */
|
||||
private boolean adminApiEnabled = false;
|
||||
|
||||
/** 내부 관리 API 접근 허용 IP(CIDR) */
|
||||
private List<String> adminAllowIps = List.of("127.0.0.1/32");
|
||||
|
||||
/** apikey 전용 DB 설정(기본값 포함) */
|
||||
private Db db = new Db();
|
||||
|
||||
/** apikey 전용 JPA 옵션 */
|
||||
private Jpa jpa = new Jpa();
|
||||
|
||||
@Getter @Setter
|
||||
public static class Jpa {
|
||||
/** hibernate.show_sql */
|
||||
private boolean showSql = false;
|
||||
|
||||
/** hibernate.format_sql */
|
||||
private boolean formatSql = false;
|
||||
}
|
||||
|
||||
|
||||
@Getter @Setter
|
||||
public static class Db {
|
||||
//내부 통신용 url
|
||||
private String url =
|
||||
"jdbc:mysql://db-md87m-kr.vpc-pub-cdb.ntruss.com:3306/kri_common?characterEncoding=UTF-8";
|
||||
private String username = "kriit";
|
||||
private String password = "it#51304";
|
||||
private String driverClassName = "com.mysql.cj.jdbc.Driver";
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package com.kri.common.auth.apikey;
|
||||
|
||||
import com.kri.common.auth.jwt.JwtUserClaimsDto;
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.kri.common.auth.apikey;
|
||||
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import com.kri.common.auth.persistence.entity.TApiKeyEntity;
|
||||
import com.kri.common.auth.persistence.repository.ApiKeyRepository;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
|
||||
public class PreloadedApiKeyUserClaimsProvider implements ApiKeyUserClaimsProvider, ApplicationRunner {
|
||||
|
||||
private final ApiKeyProperties props;
|
||||
private final ApiKeyRepository repo;
|
||||
|
||||
/** 캐시를 통째로 교체(swap)하기 위한 AtomicReference */
|
||||
private final AtomicReference<Map<String, JwtUserClaimsDto>> cacheRef =
|
||||
new AtomicReference<>(Collections.emptyMap());
|
||||
|
||||
public PreloadedApiKeyUserClaimsProvider(ApiKeyProperties props, ApiKeyRepository repo) {
|
||||
this.props = props;
|
||||
this.repo = repo;
|
||||
}
|
||||
|
||||
/** 런타임에는 DB 조회 금지: 캐시만 조회 */
|
||||
@Override
|
||||
public Optional<JwtUserClaimsDto> findUserByApiKey(String apiKey) {
|
||||
if (!StringUtils.hasText(apiKey)) return Optional.empty();
|
||||
return Optional.ofNullable(cacheRef.get().get(apiKey));
|
||||
}
|
||||
|
||||
/** 기동 시 preload */
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
if (!props.isEnabled()) return;
|
||||
if (!props.isPreloadOnStartup()) return;
|
||||
reloadFromDb();
|
||||
}
|
||||
|
||||
/** 운영용: DB에서 다시 읽어 캐시 전체 교체 */
|
||||
public synchronized int reloadFromDb() {
|
||||
if (!StringUtils.hasText(props.getServiceCode())) {
|
||||
// serviceCode 없으면 preload 불가 → 안전하게 빈 캐시
|
||||
cacheRef.set(Collections.emptyMap());
|
||||
return 0;
|
||||
}
|
||||
|
||||
var list = repo.findActiveKeysForService(props.getServiceCode());
|
||||
|
||||
Map<String, JwtUserClaimsDto> next = new ConcurrentHashMap<>(Math.max(16, list.size()));
|
||||
for (TApiKeyEntity e : list) {
|
||||
next.put(e.getApiKey(), JwtUserClaimsDto.builder()
|
||||
.userId(e.getUserId())
|
||||
.userCmpn(e.getUserCmpn())
|
||||
.userTeam(e.getUserTeam())
|
||||
.userName(e.getUserName())
|
||||
.userRole(e.getUserRole())
|
||||
.build());
|
||||
}
|
||||
|
||||
cacheRef.set(Collections.unmodifiableMap(next));
|
||||
return next.size();
|
||||
}
|
||||
|
||||
/** Admin 조회용(마스킹은 컨트롤러에서) */
|
||||
public Map<String, JwtUserClaimsDto> snapshot() {
|
||||
return cacheRef.get();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.kri.common.auth.jwt;
|
||||
package com.kri.common.auth.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Builder;
|
||||
@@ -5,7 +5,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@ConfigurationProperties(prefix = "kri.auth.jwt")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.kri.common.auth.jwt;
|
||||
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import io.jsonwebtoken.*;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.kri.common.auth.persistence.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.ColumnDefault;
|
||||
import org.hibernate.annotations.JdbcTypeCode;
|
||||
import org.hibernate.type.SqlTypes;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
@Table(name = "t_api_key")
|
||||
public class TApiKeyEntity {
|
||||
@Id
|
||||
@Column(name = "api_key", nullable = false, length = 256)
|
||||
private String apiKey;
|
||||
|
||||
/** 1=ACTIVE, 0=REVOKED */
|
||||
@Column(name = "status", nullable = false)
|
||||
@ColumnDefault("1")
|
||||
private Short status;
|
||||
|
||||
@Column(name = "user_id", nullable = false, length = 32)
|
||||
private String userId;
|
||||
|
||||
@Column(name = "user_cmpn", length = 64)
|
||||
private String userCmpn;
|
||||
|
||||
@Column(name = "user_team", length = 64)
|
||||
private String userTeam;
|
||||
|
||||
@Column(name = "user_name", length = 64)
|
||||
private String userName;
|
||||
|
||||
@Column(name = "user_role", nullable = false)
|
||||
private Integer userRole;
|
||||
|
||||
/*기본 정보 외*/
|
||||
@Column(name = "user_json")
|
||||
@JdbcTypeCode(SqlTypes.JSON)
|
||||
private Map<String, Object> userJson;
|
||||
|
||||
@Column(name = "reg_user", nullable = false, length = 32)
|
||||
private String regUser;
|
||||
|
||||
@Column(name = "reg_dt", nullable = false)
|
||||
@ColumnDefault("CURRENT_TIMESTAMP")
|
||||
private LocalDateTime regDt;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.kri.common.auth.persistence.entity;
|
||||
|
||||
import jakarta.persistence.EmbeddedId;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
@Table(name = "t_api_key_service_map")
|
||||
public class TApiKeyServiceMapEntity {
|
||||
@EmbeddedId
|
||||
private TApiKeyServiceMapEntityId id;
|
||||
|
||||
public String getApiKey() { return id.getApiKey(); }
|
||||
|
||||
public String getServiceCode() { return id.getServiceCode(); }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.kri.common.auth.persistence.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Embeddable;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.Hibernate;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Embeddable
|
||||
public class TApiKeyServiceMapEntityId implements Serializable {
|
||||
@NotNull
|
||||
@Column(name = "api_key", nullable = false, length = 256)
|
||||
private String apiKey;
|
||||
|
||||
@NotNull
|
||||
@Column(name = "service_code", nullable = false, length = 64)
|
||||
private String serviceCode;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
|
||||
TApiKeyServiceMapEntityId entity = (TApiKeyServiceMapEntityId) o;
|
||||
return Objects.equals(this.apiKey, entity.apiKey) &&
|
||||
Objects.equals(this.serviceCode, entity.serviceCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(apiKey, serviceCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.kri.common.auth.persistence.repository;
|
||||
|
||||
import com.kri.common.auth.persistence.entity.TApiKeyEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ApiKeyRepository extends JpaRepository<TApiKeyEntity, String> {
|
||||
/** ✅ preload: serviceCode에 허용된 ACTIVE 키들의 user claims를 한 번에 */
|
||||
@Query("""
|
||||
select a
|
||||
from TApiKeyEntity a
|
||||
join TApiKeyServiceMapEntity m on m.id.apiKey = a.apiKey
|
||||
where a.status = 1 and m.id.serviceCode = :serviceCode
|
||||
""")
|
||||
List<TApiKeyEntity> findActiveKeysForService(@Param("serviceCode")String serviceCode);
|
||||
}
|
||||
37
src/main/java/com/kri/common/jpa/BaseUuidEntity.java
Normal file
37
src/main/java/com/kri/common/jpa/BaseUuidEntity.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package com.kri.common.jpa;
|
||||
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.PrePersist;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@MappedSuperclass
|
||||
public abstract class BaseUuidEntity {
|
||||
protected abstract String getId();
|
||||
protected abstract void setId(String id);
|
||||
|
||||
/** 엔티티마다 컬럼 길이에 맞춰 오버라이드 */
|
||||
protected int idLength() { return 32; }
|
||||
|
||||
@PrePersist
|
||||
protected void prePersistId() {
|
||||
if (getId() == null || getId().isBlank()) {
|
||||
setId(generateId(idLength()));
|
||||
}
|
||||
}
|
||||
|
||||
private static String generateId(int length) {
|
||||
String base = UUID.randomUUID().toString().replace("-", ""); // 32 chars
|
||||
|
||||
if (length <= 32) {
|
||||
return base.substring(0, length);
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder(length);
|
||||
sb.append(base);
|
||||
while (sb.length() < length) {
|
||||
sb.append(UUID.randomUUID().toString().replace("-", ""));
|
||||
}
|
||||
return sb.substring(0, length);
|
||||
}
|
||||
}
|
||||
@@ -57,14 +57,21 @@ public class KriSwaggerAutoConfiguration {
|
||||
);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@Bean(name = "kriGroupedOpenApi")
|
||||
@ConditionalOnMissingBean(name = "kriGroupedOpenApi")
|
||||
public GroupedOpenApi kriGroupedOpenApi() {
|
||||
GroupedOpenApi.Builder builder = GroupedOpenApi.builder()
|
||||
.group("kri-api");
|
||||
if (properties.getBasePackage() != null) {
|
||||
builder.packagesToScan(properties.getBasePackage());
|
||||
.group("kri-api")
|
||||
.pathsToMatch("/api/**", "/internal/**");
|
||||
|
||||
String base = properties.getBasePackage();
|
||||
if (base != null && !base.isBlank()) {
|
||||
builder.packagesToScan(
|
||||
base,
|
||||
"com.kri.common.auth.apikey"
|
||||
);
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.kri.common.webmvc;
|
||||
|
||||
import com.kri.common.auth.jwt.JwtService;
|
||||
import com.kri.common.auth.jwt.JwtUserClaimsDto;
|
||||
import com.kri.common.auth.dto.JwtUserClaimsDto;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
com.kri.common.auth.jwt.JwtAutoConfiguration
|
||||
com.kri.common.auth.apikey.ApiKeyJpaAutoConfiguration
|
||||
com.kri.common.auth.apikey.ApiKeyPreloadAutoConfiguration
|
||||
com.kri.common.auth.apikey.ApiKeyAdminAutoConfiguration
|
||||
|
||||
com.kri.common.security.KriSecurityAutoConfiguration
|
||||
com.kri.common.web.CommonWebAutoConfiguration
|
||||
com.kri.common.webmvc.KriWebMvcAutoConfiguration
|
||||
|
||||
Reference in New Issue
Block a user