Gateway中Spring Security6统一处理CORS

文章目录

一、起因

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

于是我在system对应的controller上加了@CrossOrigin,无效;配置WebMvcConfigurer,也无效。

后来发现,会不会是gatewayspring security6在一开始就拦截了CORS跨域请求,导致根本走不到后面的system配置。

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

二、解决方法

这是依赖

xml 复制代码
		<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>

这是配置

java 复制代码
@EnableWebFluxSecurity
@Configuration
public class SecurityConfig {

    //安全拦截配置
    @Bean
    public 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();
    }

    @Bean
    public 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是一个浏览器的策略,只要处理一次,告诉浏览器我允许跨域,浏览器收到后就不再阻拦请求了。

相关推荐
BricheersZ10 分钟前
LangChain4J-(1)-Hello World
java·人工智能·langchain
回家路上绕了弯11 分钟前
Spring ApplicationContext 源码深度剖析:容器的核心引擎
java·spring
心月狐的流火号20 分钟前
线程池ThreadPoolExecutor源码分析(JDK 17)
java·源码阅读
AAA修煤气灶刘哥1 小时前
手把手教你Mybatis-Plus :小白看完都能会,看完还不回找我,我给你补个蛋
java·后端
悦人楼1 小时前
当C#遇上Notepad++:实现GCode可视化编辑的跨界实践
java·c#·notepad++
阿里云云原生1 小时前
邀您参与 “直通乌镇” Spring AI Alibaba 开源竞技挑战赛!
spring
bug菌1 小时前
🤔当类被注解为@Service后,会有什么好处?
java·后端·spring
别来无恙1493 小时前
Java 8 Stream API 完全指南:优雅处理集合数据
java·开发语言·streamapi
freed_Day3 小时前
Java进阶学习之不可变集合
java·学习
猫头虎3 小时前
如何实现在多跳UDP传输场景,保证单文件和多文件完整传输的成功率?
java·开发语言·网络·python·网络协议·golang·udp