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;
    }
}
相关推荐
sniper_fandc2 小时前
Spring Cloud系列—SkyWalking告警和飞书接入
spring cloud·skywalking
abigalexy19 小时前
深入图解Spring Cloud底层设计
spring·spring cloud
楠有枝2 天前
普通用户使用docker命令
spring cloud·docker·eureka
孤狼程序员2 天前
【Spring Cloud 微服务】2.守护神网关Gateway
spring cloud·微服务·gateway
朱皮皮呀3 天前
Spring Cloud——服务注册与服务发现原理与实现
运维·spring cloud·eureka·服务发现·php
朱皮皮呀3 天前
微服务流量分发核心:Spring Cloud 负载均衡解析
spring cloud·微服务·负载均衡
whz-emm4 天前
vLLM加载lora
gateway
源码宝5 天前
【智慧工地源码】智慧工地云平台系统,涵盖安全、质量、环境、人员和设备五大管理模块,实现实时监控、智能预警和数据分析。
java·大数据·spring cloud·数据分析·源码·智慧工地·云平台
2301_793086875 天前
SpringCloud 07 微服务网关
java·spring cloud·微服务
青衫客366 天前
Portkey-AI gateway 的一次“假压缩头”翻车的完整排障记:由 httpx 解压异常引发的根因分析
大模型·llm·gateway·httpx