统一甲屿云命名体系

This commit is contained in:
2026-06-29 23:26:43 +08:00
parent 48c47fe3ff
commit bc8a7d8d4c
1268 changed files with 3477 additions and 3511 deletions
@@ -0,0 +1,15 @@
package com.xiaowang.jayucloud.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class JayuCloudGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(JayuCloudGatewayApplication.class, args);
}
}
@@ -0,0 +1,35 @@
package com.xiaowang.jayucloud.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
/**
* Gateway CORS 配置
*
* @author xiaowang
* @date 2026-02-13
*/
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsWebFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOriginPattern("*");
config.addAllowedMethod("*");
config.addAllowedHeader("*");
config.setAllowCredentials(true);
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
@@ -0,0 +1,33 @@
package com.xiaowang.jayucloud.gateway.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* 网关白名单配置。
*
* @author xiaowang
* @date 2026-02-12
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "jayu-cloud.gateway")
public class GatewayConfig {
/**
* 白名单路径列表。
*/
private List<String> whitelist;
private SlowRequest slowRequest = new SlowRequest();
@Data
public static class SlowRequest {
private boolean enabled = true;
private long thresholdMs = 300;
private boolean logResponseHeaderRequestId = true;
}
}
@@ -0,0 +1,20 @@
package com.xiaowang.jayucloud.gateway.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* Gateway JWT 校验配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "jayu-cloud.security.jwt")
public class JwtProperties {
private String secret = "jayu-cloud-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements";
private String issuer = "jayu-cloud";
private long clockSkewSeconds = 30;
}
@@ -0,0 +1,65 @@
package com.xiaowang.jayucloud.gateway.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/health")
@RequiredArgsConstructor
public class HealthController {
private final DiscoveryClient discoveryClient;
private final Environment environment;
@GetMapping("/check")
public Map<String, Object> check() {
Map<String, Object> result = new LinkedHashMap<>();
result.put("code", 200);
result.put("message", "Jayu Cloud gateway is running");
result.put("data", diagnosticsPayload());
return result;
}
@GetMapping("/diagnostics")
public Map<String, Object> diagnostics() {
Map<String, Object> result = new LinkedHashMap<>();
result.put("code", 200);
result.put("message", "operation successful");
result.put("data", diagnosticsPayload());
return result;
}
private Map<String, Object> diagnosticsPayload() {
Map<String, Object> diagnostics = new LinkedHashMap<>();
String serviceName = environment.getProperty("spring.application.name", "jy-gateway");
diagnostics.put("service", serviceName);
diagnostics.put("port", environment.getProperty("server.port", ""));
diagnostics.put("gatewayService", discoverySummary(serviceName));
diagnostics.put("coreService", discoverySummary("jy-core"));
return diagnostics;
}
private Map<String, Object> discoverySummary(String serviceName) {
Map<String, Object> result = new LinkedHashMap<>();
try {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
result.put("ok", !instances.isEmpty());
result.put("service", serviceName);
result.put("instanceCount", instances.size());
} catch (Exception exception) {
result.put("ok", false);
result.put("service", serviceName);
result.put("error", exception.getClass().getSimpleName());
}
return result;
}
}
@@ -0,0 +1,137 @@
package com.xiaowang.jayucloud.gateway.filter;
import com.xiaowang.jayucloud.gateway.config.GatewayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashSet;
import java.util.List;
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
private static final List<String> DEFAULT_WHITELIST = AuthWhitelist.defaultPatterns();
@Autowired
private GatewayConfig gatewayConfig;
@Autowired
private GatewayJwtValidator gatewayJwtValidator;
private final AntPathMatcher pathMatcher = new AntPathMatcher();
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String path = request.getURI().getPath();
if (isWhitelist(path)) {
return chain.filter(exchange);
}
String authorization = request.getHeaders().getFirst("Authorization");
if (!StringUtils.hasText(authorization)) {
return unAuthorized(exchange, "未携带Token,拒绝访问");
}
if (!authorization.startsWith("Bearer ")) {
return unAuthorized(exchange, "Token格式错误");
}
String token = authorization.substring("Bearer ".length());
if (!gatewayJwtValidator.validateAccessToken(token)) {
return unAuthorized(exchange, "Token无效或已过期");
}
return chain.filter(exchange);
}
private boolean isWhitelist(String path) {
return AuthWhitelist.effectivePatterns(gatewayConfig).stream()
.anyMatch(pattern -> pathMatcher.match(pattern, path));
}
private Mono<Void> unAuthorized(ServerWebExchange exchange, String msg) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
String result = "{\"code\": 401, \"message\": \"" + msg + "\", \"data\": null}";
DataBuffer buffer = response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
return response.writeWith(Mono.just(buffer));
}
@Override
public int getOrder() {
return -1;
}
public static final class AuthWhitelist {
private AuthWhitelist() {
}
public static List<String> defaultPatterns() {
return List.of(
"/api/user/login",
"/api/user/register",
"/api/user/check/**",
"/api/user/refresh-token",
"/api/user/send-verification-code",
"/api/user/phone-login",
"/api/user/wechat-mini/**",
"/api/user/reset-password-by-phone",
"/api/legal-agreement/current",
"/api/legal-agreement/current/**",
"/api/nail-artist/profile/**",
"/api/nail-artist/*/availability",
"/api/nail-artist/*/reviews",
"/api/product/get/**",
"/api/product/list/**",
"/api/comment/list/product/**",
"/api/shop/get/**",
"/api/shop/list",
"/api/shop/list/public",
"/api/shop/list/simple",
"/api/tag/list/all",
"/api/tag/list/filter-options",
"/api/file/get-signed-url/**",
"/api/admin/auth/login",
"/api/admin/auth/login-shops/**",
"/api/admin/auth/refresh",
"/admin/auth/login",
"/admin/auth/login-shops/**",
"/admin/auth/refresh",
"/admin/api/auth/login",
"/admin/api/auth/login-shops/**",
"/admin/api/auth/refresh",
"/api/health/**",
"/api/error"
);
}
public static List<String> effectivePatterns(GatewayConfig gatewayConfig) {
if (gatewayConfig == null || gatewayConfig.getWhitelist() == null || gatewayConfig.getWhitelist().isEmpty()) {
return defaultPatterns();
}
LinkedHashSet<String> patterns = new LinkedHashSet<>(gatewayConfig.getWhitelist());
patterns.addAll(DEFAULT_WHITELIST);
return List.copyOf(patterns);
}
}
}
@@ -0,0 +1,40 @@
package com.xiaowang.jayucloud.gateway.filter;
import com.xiaowang.jayucloud.gateway.config.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
/**
* Gateway 侧 JWT 快速校验。
*/
@Component
@RequiredArgsConstructor
public class GatewayJwtValidator {
private final JwtProperties jwtProperties;
public boolean validateAccessToken(String token) {
try {
Claims claims = Jwts.parserBuilder()
.setSigningKey(getKey())
.setAllowedClockSkewSeconds(jwtProperties.getClockSkewSeconds())
.requireIssuer(jwtProperties.getIssuer())
.build()
.parseClaimsJws(token)
.getBody();
return "access".equals(claims.get("type", String.class));
} catch (Exception exception) {
return false;
}
}
private SecretKey getKey() {
return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8));
}
}
@@ -0,0 +1,114 @@
package com.xiaowang.jayucloud.gateway.filter;
import com.xiaowang.jayucloud.gateway.config.GatewayConfig;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.InetSocketAddress;
import java.util.UUID;
@Component
@RequiredArgsConstructor
public class SlowRequestLoggingGlobalFilter implements GlobalFilter, Ordered {
public static final String REQUEST_ID_HEADER = "X-Request-Id";
private static final Logger SLOW_REQUEST_LOGGER = LoggerFactory.getLogger("gateway-slow");
private final GatewayConfig gatewayConfig;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest originalRequest = exchange.getRequest();
String requestId = resolveRequestId(originalRequest.getHeaders());
ServerHttpRequest decoratedRequest = originalRequest.mutate()
.headers(headers -> headers.set(REQUEST_ID_HEADER, requestId))
.build();
ServerWebExchange decoratedExchange = exchange.mutate().request(decoratedRequest).build();
GatewayConfig.SlowRequest slowRequest = gatewayConfig.getSlowRequest();
if (slowRequest != null && slowRequest.isLogResponseHeaderRequestId()) {
decoratedExchange.getResponse().getHeaders().set(REQUEST_ID_HEADER, requestId);
}
if (slowRequest == null || !slowRequest.isEnabled()) {
return chain.filter(decoratedExchange);
}
long startNanos = System.nanoTime();
return chain.filter(decoratedExchange)
.doFinally(signalType -> logIfSlow(decoratedExchange, requestId, startNanos, slowRequest.getThresholdMs()));
}
@Override
public int getOrder() {
return -2;
}
private void logIfSlow(ServerWebExchange exchange, String requestId, long startNanos, long thresholdMs) {
long durationMs = Math.max(0L, (System.nanoTime() - startNanos) / 1_000_000L);
if (durationMs < thresholdMs) {
return;
}
ServerHttpRequest request = exchange.getRequest();
Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
String query = request.getURI().getRawQuery();
String routeId = route == null ? "" : route.getId();
String status = exchange.getResponse().getStatusCode() == null
? ""
: String.valueOf(exchange.getResponse().getStatusCode().value());
SLOW_REQUEST_LOGGER.warn(
"requestId={} method={} path={} query={} routeId={} status={} durationMs={} clientIp={} userAgent={} contentLength={}",
requestId,
request.getMethodValue(),
request.getURI().getPath(),
sanitize(query),
sanitize(routeId),
status,
durationMs,
resolveClientIp(request),
sanitize(request.getHeaders().getFirst(HttpHeaders.USER_AGENT)),
request.getHeaders().getContentLength()
);
}
private String resolveRequestId(HttpHeaders headers) {
String requestId = headers.getFirst(REQUEST_ID_HEADER);
return StringUtils.hasText(requestId) ? requestId.trim() : UUID.randomUUID().toString().replace("-", "");
}
private String resolveClientIp(ServerHttpRequest request) {
String forwarded = request.getHeaders().getFirst("X-Forwarded-For");
if (StringUtils.hasText(forwarded)) {
return forwarded.split(",")[0].trim();
}
String realIp = request.getHeaders().getFirst("X-Real-IP");
if (StringUtils.hasText(realIp)) {
return realIp.trim();
}
InetSocketAddress remoteAddress = request.getRemoteAddress();
return remoteAddress == null || remoteAddress.getAddress() == null
? ""
: remoteAddress.getAddress().getHostAddress();
}
private String sanitize(String value) {
if (!StringUtils.hasText(value)) {
return "";
}
return value.replace('\n', '_').replace('\r', '_');
}
}
@@ -0,0 +1,163 @@
spring:
cloud:
gateway:
routes:
# 前台API路由
- id: product-route
uri: lb://jy-core
predicates:
- Path=/api/product/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: product-like-route
uri: lb://jy-core
predicates:
- Path=/api/product-like/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: shop-route
uri: lb://jy-core
predicates:
- Path=/api/shop/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: user-route
uri: lb://jy-core
predicates:
- Path=/api/user/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: comment-route
uri: lb://jy-core
predicates:
- Path=/api/comment/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: balance-route
uri: lb://jy-core
predicates:
- Path=/api/balance/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: tag-route
uri: lb://jy-core
predicates:
- Path=/api/tag/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: file-route
uri: lb://jy-core
predicates:
- Path=/api/file/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: permission-route
uri: lb://jy-core
predicates:
- Path=/api/permission/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: coupon-route
uri: lb://jy-core
predicates:
- Path=/api/coupon/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: cart-route
uri: lb://jy-core
predicates:
- Path=/api/cart/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: order-route
uri: lb://jy-core
predicates:
- Path=/api/order/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: wishlist-route
uri: lb://jy-core
predicates:
- Path=/api/wishlist/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: nail-artist-route
uri: lb://jy-core
predicates:
- Path=/api/nail-artist/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
- id: legal-agreement-route
uri: lb://jy-core
predicates:
- Path=/api/legal-agreement/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
# 后台管理API路由(/api/admin/** 格式)
- id: admin-api-route
order: -10
uri: lb://jy-core
predicates:
- Path=/api/admin/**
filters:
- RewritePath=/api/admin/(?<remaining>.*), /admin/${remaining}
# 后台管理API路由(/admin/api/** 格式)
- id: admin-route
order: -9
uri: lb://jy-core
predicates:
- Path=/admin/api/**
filters:
- RewritePath=/admin/api/(?<remaining>.*), /admin/${remaining}
- id: admin-auth-compat-route
order: -8
uri: lb://jy-core
predicates:
- Path=/admin/auth/**
# 前台API兜底路由,避免 Core 新增模块后 Gateway 未同步导致 404
- id: frontend-fallback-route
order: 100
uri: lb://jy-core
predicates:
- Path=/api/**
filters:
- RewritePath=/api/(?<remaining>.*), /${remaining}
jayu-cloud:
security:
jwt:
issuer: jayu-cloud
clock-skew-seconds: 30
gateway:
whitelist:
- /api/user/login
- /api/user/register
- /api/user/check/**
- /api/user/refresh-token
- /api/user/send-verification-code
- /api/user/phone-login
- /api/user/wechat-mini/**
- /api/user/reset-password-by-phone
- /api/nail-artist/profile/**
- /api/nail-artist/*/availability
- /api/nail-artist/*/reviews
- /api/shop/list
- /api/shop/list/simple
- /api/legal-agreement/current
- /api/legal-agreement/current/**
- /api/health/**
- /api/error
- /api/admin/auth/login
- /api/admin/auth/login-shops/**
- /api/admin/auth/refresh
- /api/admin/auth/register
- /admin/auth/login
- /admin/auth/login-shops/**
- /admin/auth/refresh
- /admin/api/auth/login
- /admin/api/auth/login-shops/**
- /admin/api/auth/refresh
slow-request:
enabled: true
threshold-ms: 300
log-response-header-request-id: true
@@ -0,0 +1,45 @@
spring:
application:
name: jy-gateway
cloud:
nacos:
discovery:
# Nacos 集群地址,默认指向开发环境,生产环境通过环境变量覆盖。
server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848}
# Nacos 命名空间,默认指向开发环境
namespace: jayu-cloud-dev
# 服务注册分组。
group: ${NACOS_GROUP:DEFAULT_GROUP}
# 注册到 Nacos 的服务名。
service: ${spring.application.name}
# Nacos 认证用户名。
username: ${NACOS_USERNAME:xiaowang}
# Nacos 认证密码。
password: ${NACOS_PASSWORD:122503wcy....}
config:
# Nacos 配置中心地址,与服务发现使用同一组集群节点,默认指向开发环境。
server-addr: ${NACOS_SERVER_ADDR:192.168.5.103:8848}
# Nacos 配置中心命名空间,默认指向开发环境。
namespace: jayu-cloud-dev
# 配置分组。
group: ${NACOS_GROUP:DEFAULT_GROUP}
# Gateway 服务独有配置文件。
name: gateway
# 所有 Nacos 配置均使用 YAML。
file-extension: yaml
# Nacos 认证用户名。
username: ${NACOS_USERNAME:xiaowang}
# Nacos 认证密码。
password: ${NACOS_PASSWORD:122503wcy....}
# Core 与 Gateway 共享的公共配置文件。
shared-configs:
- data-id: infra.yaml
group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
- data-id: secret.yaml
group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
- data-id: logging.yaml
group: ${NACOS_GROUP:DEFAULT_GROUP}
refresh: true
+81
View File
@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property>
<Property name="LOG_HOME">E:/code/xiaowang/JY-Gateway/logs</Property>
</Properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
<RollingFile name="RollingFile" fileName="${LOG_HOME}/jy-gateway.log"
filePattern="${LOG_HOME}/jy-gateway-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
<DefaultRolloverStrategy max="30">
<Delete basePath="${LOG_HOME}" maxDepth="1">
<IfFileName glob="jy-gateway-*.log.gz"/>
<IfLastModified age="30d"/>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
<RollingFile name="ErrorRollingFile" fileName="${LOG_HOME}/jy-gateway-error.log"
filePattern="${LOG_HOME}/jy-gateway-error-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="${LOG_PATTERN}"/>
<ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
<DefaultRolloverStrategy max="30">
<Delete basePath="${LOG_HOME}" maxDepth="1">
<IfFileName glob="jy-gateway-error-*.log.gz"/>
<IfLastModified age="30d"/>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
<RollingFile name="SlowRollingFile" fileName="${LOG_HOME}/jy-gateway-slow.log"
filePattern="${LOG_HOME}/jy-gateway-slow-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
<DefaultRolloverStrategy max="30">
<Delete basePath="${LOG_HOME}" maxDepth="1">
<IfFileName glob="jy-gateway-slow-*.log.gz"/>
<IfLastModified age="30d"/>
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="Console"/>
<AppenderRef ref="RollingFile"/>
<AppenderRef ref="ErrorRollingFile"/>
</Root>
<Logger name="com.xiaowang.jayucloud.gateway" level="INFO" additivity="false">
<AppenderRef ref="Console"/>
<AppenderRef ref="RollingFile"/>
<AppenderRef ref="ErrorRollingFile"/>
</Logger>
<Logger name="gateway-slow" level="WARN" additivity="false">
<AppenderRef ref="SlowRollingFile"/>
</Logger>
<Logger name="org.springframework" level="INFO"/>
<Logger name="com.alibaba.nacos" level="INFO"/>
</Loggers>
</Configuration>
@@ -0,0 +1,73 @@
package com.xiaowang.jayucloud.gateway.filter;
import com.xiaowang.jayucloud.gateway.config.GatewayConfig;
import com.xiaowang.jayucloud.gateway.filter.AuthGlobalFilter.AuthWhitelist;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.AntPathMatcher;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class AuthGlobalFilterWhitelistTest {
private final AntPathMatcher pathMatcher = new AntPathMatcher();
@Test
void effectiveWhitelistCoversPublicCommentListAndRejectsOrderApi() {
GatewayConfig config = new GatewayConfig();
config.setWhitelist(List.of("/api/user/login"));
List<String> patterns = AuthWhitelist.effectivePatterns(config);
assertThat(matches(patterns, "/api/comment/list/product/1")).isTrue();
assertThat(matches(patterns, "/api/order/list")).isFalse();
assertThat(matches(patterns, "/api/admin/user/list")).isFalse();
}
@Test
void defaultWhitelistIncludesOnlyExpectedPublicBusinessAreas() {
assertThat(AuthWhitelist.defaultPatterns())
.contains(
"/api/user/login",
"/api/comment/list/product/**",
"/api/admin/auth/login",
"/admin/auth/login",
"/api/nail-artist/profile/**",
"/api/nail-artist/*/availability",
"/api/nail-artist/*/reviews",
"/api/shop/list"
)
.doesNotContain("/api/order/**", "/api/shop/delete/**", "/api/permission/**");
}
@Test
void directAdminLoginCompatibilityPathIsWhitelisted() {
assertThat(matches(AuthWhitelist.defaultPatterns(), "/admin/auth/login")).isTrue();
assertThat(matches(AuthWhitelist.defaultPatterns(), "/admin/auth/login-shops/1")).isTrue();
assertThat(matches(AuthWhitelist.defaultPatterns(), "/admin/auth/refresh")).isTrue();
}
@Test
void applicationRoutesDirectAdminAuthCompatibilityPath() throws Exception {
String yaml = new String(new ClassPathResource("application.yaml").getInputStream().readAllBytes(), StandardCharsets.UTF_8);
assertThat(yaml).contains("Path=/admin/auth/**");
}
@Test
void applicationRoutesManagerApiThroughAdminRoute() throws Exception {
String yaml = new String(new ClassPathResource("application.yaml").getInputStream().readAllBytes(), StandardCharsets.UTF_8);
assertThat(yaml)
.contains("Path=/api/admin/**")
.contains("RewritePath=/api/admin/(?<remaining>.*), /admin/${remaining}");
assertThat(matches(AuthWhitelist.defaultPatterns(), "/api/admin/manager/planning/calendar")).isFalse();
}
private boolean matches(List<String> patterns, String path) {
return patterns.stream().anyMatch(pattern -> pathMatcher.match(pattern, path));
}
}