这是我第一次实施 Spring Cloud Gateway。
我需要过滤每个请求并在某些路径上应用过滤器验证。按照 Baeldung 自定义过滤器教程,我制作了一个简单的应用程序来过滤请求。
应用程序必须发布类似的路径/actuator/health
并验证后端服务的特定路径。到目前为止,我已经实现了 aGlobalFilter
和 a GatewayFilterFactory
。每个请求都会调用全局过滤器,但在应用程序启动时只调用一次 GatewayFilter,这样我就无法为每个请求创建身份验证逻辑。auth 逻辑是关于一个特定的头字段。所以,我的粒度问题是:
- 如何使用特定路径验证每个请求?
- 如何拒绝请求并发送错误消息?
全局过滤器
@Component
public class LoggingGlobalPreFilter implements GlobalFilter {
final Logger LOGGER = LoggerFactory.getLogger(LoggingGlobalPreFilter.class);
@Override
public Mono<Void> filter(
ServerWebExchange exchange,
GatewayFilterChain chain) {
LOGGER.info("Global Pre Filter executed");
return chain.filter(exchange);
}
}
网关过滤器
@Component
public class LoggingGatewayFilterFactory extends
AbstractGatewayFilterFactory<LoggingGatewayFilterFactory.Config> {
final Logger LOGGER =
LoggerFactory.getLogger(LoggingGatewayFilterFactory.class);
public LoggingGatewayFilterFactory() {
super(Config.class);
}
private Mono<Void> onError(ServerWebExchange exchange, String err, HttpStatus httpStatus) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(httpStatus);
return response.setComplete();
}
private boolean isAuthorizationValid(String authorizationHeader) {
boolean isValid = true;
return authorizationHeader.equals("x-header");
}
@Override
public GatewayFilter apply(Config config) {
LOGGER.info("M=apply, Msg=Applying Gateway Filter....");
return ((exchange, chain) -> {
LOGGER.info("M=apply, Msg=Applying Gateway Filter...."); // APARENTELLY NEVER ENTER HERE.
ServerHttpRequest request = exchange.getRequest();
if (!request.getHeaders().containsKey(TsApiGatewayConstants.HEADER_APIKEY)) {
return this.onError(exchange, TsApiGatewayConstants.MESSAGE_API_KEY_MISSING, HttpStatus.UNAUTHORIZED);
}
String apiKey = request.getHeaders().get(TsApiGatewayConstants.HEADER_APIKEY).get(0);
String userAgent = request.getHeaders().get(TsApiGatewayConstants.HEADER_USER_AGENT).get(0);
if (!this.isAuthorizationValid(userAgent)) {
return this.onError(exchange, TsApiGatewayConstants.MESSAGE_API_KEY_INVALID, HttpStatus.UNAUTHORIZED);
}
return chain.filter(exchange);
});
}
public static class Config {
private String baseMessage;
private boolean preLogger;
private boolean postLogger;
public Config(String baseMessage, boolean preLogger, boolean postLogger) {
this.baseMessage = baseMessage;
this.preLogger = preLogger;
this.postLogger = postLogger;
}
public String getBaseMessage() {
return baseMessage;
}
public void setBaseMessage(String baseMessage) {
this.baseMessage = baseMessage;
}
public boolean isPreLogger() {
return preLogger;
}
public void setPreLogger(boolean preLogger) {
this.preLogger = preLogger;
}
public boolean isPostLogger() {
return postLogger;
}
public void setPostLogger(boolean postLogger) {
this.postLogger = postLogger;
}
}
}
应用程序.yml
cloud:
gateway:
routes:
- id: service_route
uri: https://backend-url:443
predicates:
- Path=/api
filters:
- Logging
过滤器的示例路径:https://backend-url:443/api/service1