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

相关推荐
码不停蹄的玄黓22 分钟前
AQS底层原理
java
糖果店的幽灵24 分钟前
Claude Code 完全实战指南 - 第四章:Skill 怎么写
java·服务器·前端
jeffer_liu31 分钟前
Spring AI 生产级实战:记忆管理
java·人工智能·后端·spring·语言模型
憧憬成为java架构高手的小白41 分钟前
git工作流程简化版
java·spring boot·git
触底反弹44 分钟前
苹果换芯片,用户说「真香」;微软换芯片,用户说「退货」—— 同样的事,为什么结果完全相反?
java·架构·编程语言
澜舟孟子开源社区1 小时前
架构创新、上下文工程、可信计算、自适应优化:澜舟科技智能体核心技术解析
java·科技·架构
淘矿人1 小时前
DeepSeek V4对决Claude 4.8:AI模型终极横评
java·开发语言·人工智能·python·sql·php·pygame
IT利刃出鞘1 小时前
Java多线程--三种写法(Thread、Runnable、Callable)
java·多线程
两年半的个人练习生^_^2 小时前
JMM 进阶:彻底理解 volatile 实现原理
java·开发语言
Yeats_Liao2 小时前
Java网络编程(五):Selector选择器与高并发实现
java·后端·架构