当前位置: 首页 > news >正文

Gateway中Spring Security6统一处理CORS

文章目录

  • 一、起因
  • 二、解决方法

一、起因

使用了gateway微服务作为整体的网关,并且整合了Spring Security6;还有一个system微服务,作为被请求的资源,当浏览器向gateway发送请求,请求system资源时,遇到CORS问题。

于是我在system对应的controller上加了@CrossOrigin,无效;配置WebMvcConfigurer,也无效。
后来发现,会不会是gatewayspring security6在一开始就拦截了CORS跨域请求,导致根本走不到后面的system配置。

查询了一波,果然如此。这里记录解决方法。

二、解决方法

这是依赖

		<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-oauth2-resource-server</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>

这是配置

@EnableWebFluxSecurity
@Configuration
public class SecurityConfig {//安全拦截配置@Beanpublic SecurityWebFilterChain webFluxSecurityFilterChain(ServerHttpSecurity http) throws Exception {return http.cors(cors -> cors.configurationSource(corsConfigurationSource())).authorizeExchange(exchanges ->exchanges.pathMatchers("/**").permitAll().anyExchange().authenticated()).oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())).csrf(ServerHttpSecurity.CsrfSpec::disable).build();}@Beanpublic CorsConfigurationSource corsConfigurationSource() {CorsConfiguration corsConfig = new CorsConfiguration();corsConfig.addAllowedOriginPattern("*"); // 允许任何源corsConfig.addAllowedMethod("*"); // 允许任何HTTP方法corsConfig.addAllowedHeader("*"); // 允许任何HTTP头corsConfig.setAllowCredentials(true); // 允许证书(cookies)corsConfig.setMaxAge(3600L); // 预检请求的缓存时间(秒)UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", corsConfig); // 对所有路径应用这个配置return source;}
}

需要注意的是,在gatewayspring security中处理了CORS问题后,后续的system什么的,就不需要再二次处理了。因为CORS是一个浏览器的策略,只要处理一次,告诉浏览器我允许跨域,浏览器收到后就不再阻拦请求了。

http://www.lryc.cn/news/299207.html

相关文章:

  • 突破编程_C++_基础教程(输入、输出与文件)
  • UE的 HUD 类中的必备方法和属性
  • 单片机的认识
  • 转发:udig安装 用来为geoserver上shp地图配置显示样式 颜色
  • Linux--常用命令(详解)
  • SouthLeetCode-打卡24年02月第1周
  • vscode的cmake工具小三角符号旁边没有目标的解决方法
  • Servlet JSP-Eclipse安装配置Maven插件
  • os模块
  • 【C语言进阶】深度剖析数据在内存中的存储--上
  • 【doghead】VS2022 win11 安装配置WSL2 以编译linux端的cmake项目并运行2
  • 【教程】C++语言基础学习笔记(七)——Array数组
  • BUGKU-WEB GET
  • 蓝桥杯每日一题----唯一分解定理
  • openssl3.2 - osslsigncode工程的学习
  • HTML 超文本标记语言
  • sklearn:机器学习 分类特征编码category_encoders
  • C++错误[错误] call of overloaded ‘min(int, int)‘ is ambiguous
  • 2024全栈元年-thinkphp-数据操作
  • HTML世界之第二重天
  • 社区经营的好处与优势:为何越来越多的人选择社区店?
  • C语言系列1——详解C语言:变量、常量与数据类型
  • WordPress修改所有用户名并发送邮件通知的插件Easy Username Updater
  • C语言中的数据类型-强转
  • 大数据可视化BI分析工具Apache Superset结合内网穿透实现远程访问
  • C# 线程与线程池的使用方法、注意事项
  • 2024年华为OD机试真题-按身高和体重排队-Python-OD统一考试(C卷)
  • openGauss学习笔记-218 openGauss性能调优-确定性能调优范围-硬件瓶颈点分析-I/O
  • 去除vue自带的边距
  • ElasticSearch级查询Query DSL上