在构建微服务架构时,Spring Cloud Gateway 作为服务网关,承担着路由转发、权限校验等职责。
全局过滤器(Global Filter)是 Spring Cloud Gateway 中用于处理跨服务的通用逻辑的组件,例如权限验证、日志记录等。
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.core.io.buffer.DataBufferFactory;
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.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {
private AntPathMatcher antPathMatcher = new AntPathMatcher();
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest serverHttpRequest = exchange.getRequest();
String path = serverHttpRequest.getURI().getPath();
// 判断路径中是否包含 "inner",只允许内部调用
if (antPathMatcher.match("/**/inner/**", path)) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.FORBIDDEN);
DataBufferFactory dataBufferFactory = response.bufferFactory();
DataBuffer dataBuffer = dataBufferFactory.wrap("无权限".getBytes(StandardCharsets.UTF_8));
return response.writeWith(Mono.just(dataBuffer));
}
// 统一权限校验,此处应添加JWT等验证逻辑
// todo 统一权限校验,通过 JWT 获取登录用户信息
return chain.filter(exchange);
}
/**
* 设置过滤器的优先级
* 值越小,优先级越高
* @return
*/
@Override
public int getOrder() {
return 0;
}
}