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

相关推荐
皙然4 分钟前
吃透进程与线程:从概念到实战,破解并发编程核心难题
java·开发语言
冬夜戏雪5 分钟前
HashMAP底层原理和扰动hash的例子
java·开发语言
咸鱼2.05 分钟前
【java入门到放弃】计算机网络
java·开发语言·计算机网络
Zzxy8 分钟前
MyBatis-Plus入门
java·mybatis
木井巳8 分钟前
【递归算法】找出所有子集的异或总和再求和
java·算法·leetcode·决策树·深度优先
悟空码字11 分钟前
【保姆级】实现APP分享至微信,看完就能落地
java·后端·微信
常利兵13 分钟前
Android 开发探秘:View.post()为何能获取View宽高
java·数据库·sql
闭关苦炼内功13 分钟前
使用Java语言实现二分查找
java·开发语言
毕设源码-郭学长15 分钟前
【开题答辩全过程】以 基于Spring Boot“活力青春”健身房管理系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
m0_4750645017 分钟前
Spring AI RAG简易demo
java·人工智能·spring