Spring Cloud之Gateway网关过滤器(URL黑名单)
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class BlacklistFilter implements GlobalFilter {
private final List<String> blacklist;
public BlacklistFilter(List<String> blacklist) {
this.blacklist = blacklist;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String path = exchange.getRequest().getURI().getPath();
// 检查请求路径是否在黑名单中
if (blacklist.stream().anyMatch(path::startsWith)) {
// 如果在黑名单中,返回403禁止访问
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.FORBIDDEN);
// 可以返回更友好的错误信息
byte[] bytes = "You are not allowed to access this resource".getBytes(StandardCharsets.UTF_8);
DataBufferUtils.write(response.bufferFactory().wrap(bytes), response.getBody());
return exchange.getResponse().setComplete();
}
// 如果不在黑名单中,继续请求处理
return chain.filter(exchange);
}
}
这段代码定义了一个名为BlacklistFilter
的全局过滤器,用于检查请求的路径是否在黑名单中。如果在黑名单中,过滤器将返回HTTP状态码403,表示禁止访问。这是一个简单的示例,展示了如何在Spring Cloud Gateway中实现基于路径的访问控制。
评论已关闭