SpringCloud Gateway网关 全局过滤器[AntPathMatcher 某些路径url禁止访问] 实现用户鉴权

前提:先保证Gateway网关项目 和 Nacos注册中心 等可以正常访问和调用,搭建方法可查看博文

SpringCloud Gateway网关 项目创建 及 整合Nacos开发_spring gateway如何设置工程名称-CSDN博客

类似的全局鉴权方案,参考如下:
SpringCloud Gateway网关 全局过滤器header token 实现用户鉴权_gateway添加鉴权过滤器-CSDN博客

核心代码如下:

复制代码
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();
        
        // 判断路径中是否包含 system,如果包含system,则不允许访问
        if (antPathMatcher.match("/**/system/**", path)) {

            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            response.setStatusCode(HttpStatus.FORBIDDEN);
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            DataBuffer dataBuffer = dataBufferFactory.wrap("无权限".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));

            //设置状态码 未授权401
            //exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            //个人理解,终止输出访问
            //return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 优先级提到最高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
相关推荐
captain3769 小时前
SpringCloud(12)-Gateway
spring boot·spring cloud·gateway
行百里er1 天前
【Spring Insight 技术分享】如何让 AI 解释失败也不拖垮控制台
后端·spring cloud·开源
行百里er2 天前
【Spring Insight 技术分享】如何给 AI 接口调用做滑动窗口限流
spring boot·后端·spring cloud
如夏倾城5 天前
BGP(Border Gateway Protocol 边界网关协议)
运维·服务器·网络·gateway·信息与通信
逃逸线LOF7 天前
SpringCloud Stream
后端·spring·spring cloud
JJJennie7779 天前
MAI Gateway 免费试用与付费方案详解:先验效果,再谈 ROI
人工智能·大模型·gateway·ai网关
wz975410 天前
Docker 从 systemd 托管容器、overlay2 存储驱动到 Compose 多容器实战
spring cloud·docker·eureka
顧棟12 天前
INFINI Gateway 服务器端口重用(SO_REUSEPORT)实现与分析
网络·gateway
逃逸线LOF14 天前
服务网关Gateway
java·运维·gateway
小郎君65815 天前
注解式脱敏:用 Jackson 的 ContextualSerializer 做字段级策略(一)
spring boot·spring cloud