修改服务转发方式
This commit is contained in:
@ -6,25 +6,53 @@ import org.springframework.cloud.gateway.filter.GlobalFilter;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
|
||||
import org.springframework.core.Ordered;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.PathMatcher;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AuthGlobalFilter implements GlobalFilter, Ordered {
|
||||
|
||||
|
||||
// ✅ 支持通配符路径
|
||||
private static final PathMatcher PATH_MATCHER = new AntPathMatcher();
|
||||
private static final List<String> ALLOW_PATH_PATTERNS = Arrays.asList("/zc/user/test", "/zc/user/register", "/zc/user/auth/**", "/zc/**/swagger-ui/**", "/zc/**/v3/api-docs");
|
||||
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
|
||||
String path = exchange.getRequest().getPath().value();
|
||||
log.info("🌐 请求路径: {}", path);
|
||||
|
||||
// ✅ 检查路径是否放行
|
||||
boolean isAllowed = ALLOW_PATH_PATTERNS.stream().anyMatch(pattern -> PATH_MATCHER.match(pattern, path));
|
||||
log.info("是否放行: {}", isAllowed);
|
||||
|
||||
// 示例:拦截所有请求,校验 token
|
||||
// String token = exchange.getRequest().getHeaders().getFirst("Authorization");
|
||||
// if (token == null || !token.startsWith("Bearer ")) {
|
||||
// exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
|
||||
// return exchange.getResponse().setComplete();
|
||||
// }
|
||||
if (!isAllowed) {
|
||||
// 非放行路径,校验 token
|
||||
String token = exchange.getRequest().getHeaders().getFirst("Authorization");
|
||||
if (token == null || !token.startsWith("Bearer ")) {
|
||||
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
String errorBody = "{\"code\":401,\"message\":\"Unauthorized\"}";
|
||||
|
||||
return exchange.getResponse().writeWith(Mono.just(exchange.getResponse()
|
||||
.bufferFactory().wrap(errorBody.getBytes())));
|
||||
}
|
||||
}
|
||||
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user