springCloudGateway网关配置

1.配置跨域支持

复制代码
/**
 * 跨域支持
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource source =
                new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}

2.yml配置

复制代码
server:
  port: 8888
spring:
  profiles:
    active: prod
  application:
    name: tanhua-gateway
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.136.160:8848
    gateway:
      globalcors:
        add-to-simple-url-handler-mapping: true
        corsConfigurations:
          '[/**]':
            allowedHeaders: "*"
            allowedOrigins: "*"
            allowedMethods:
              - GET
              - POST
              - DELETE
              - PUT
              - OPTION
      routes:
        # 探花系统
        - id: tanhua-app-server
          uri: lb://tanhua-app-server
          predicates:
            - Path=/app/**
          filters:
            - StripPrefix= 1
        # 后台系统
        - id: tanhua-admin
          uri: lb://tanhua-admin
          predicates:
            - Path=/admin/**
          # 路径截取配置
          filters:
            - StripPrefix= 1
gateway:
  excludedUrls: /user/login,/user/loginVerification,/system/users/verification,/system/users/login

3.网关鉴权

复制代码
public class AuthFilter implements GlobalFilter, Ordered {
    @Value("${gateway.excludedUrls}")
    private List<String> excludedUrls;//需要配置不校验的连接
    //过滤器核心业务代码
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //排除不需要权限检验的连接
        for (String excludedUrl : excludedUrls) {
            System.out.println(excludedUrl);
        }
        String path = exchange.getRequest().getURI().getPath();//当前请求连接
        System.out.println("url"+path);
        if(excludedUrls.contains(path)){
            return chain.filter(exchange);
        }
        //获取token并校验
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if(!StringUtils.isEmpty(token)){
            token=token.replaceAll("Bearer ","");
        }
        boolean verifyToken = JwtUtils.verifyToken(token);
        //如果校验失败,响应错误状态401
        if(!verifyToken){
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("errCode", 401);
            responseData.put("errMessage", "用户未登录");
            return responseError(exchange.getResponse(),responseData);
        }
        return chain.filter(exchange);
    }

    //配置执行顺序
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }

    private Mono<Void> responseError(ServerHttpResponse response, Map<String, Object> responseData){
        // 将信息转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] data = new byte[0];
        try {
            data = objectMapper.writeValueAsBytes(responseData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 输出错误信息到页面
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

}
相关推荐
CoderYanger4 分钟前
Java EE 进阶:6.SpringBoot 配置文件(第二弹)
java·spring boot·spring·面试·职场和发展·java-ee·程序员创富
MaAidan5 分钟前
用 Agent 排查线上问题:SLS 日志分析 + DB/Redis 数据验证,一条链路搞清楚
前端·bootstrap·html
文丑颜不良啊6 分钟前
LeetCode1681~1700题目解析
java·leetcode
愚农搬码10 分钟前
电子表单、动态表单、表单设计器和表单引擎到底有什么区别?
java·后端
CarIise13 分钟前
Spring 框架AOP与 XML 基础
java·开发语言
m0_6399069417 分钟前
SpringBoot 实现大模型统一调度网关|对接 OpenAI、Claude 协议差异与适配方案
java·spring boot·spring
雪芽蓝域zzs18 分钟前
第 1 章:IDEA 全局配置 Maven + 新建 SpringBoot3 Maven 项目
java·maven·intellij-idea
墨林陌20 分钟前
AI 热点日报(2026-11-03):美团发布 1.6 万亿参数国产大模型,四大厂商共推 AI 训练退出标准
前端
Moment26 分钟前
DeepSeek 发布新模型,直接把 Agent 联网搜索的门槛打下来了!
前端·后端
AI宇宙狂想家32 分钟前
开源 AI 视频工具进化史:从难用到好用,OpenMontage 改了什么
开发语言·前端·人工智能·开源·ai创业·openmontage