spring boot 2.4.x 跨域配置

spring boot 2.4.x 跨域配置


	@Bean
	public CorsFilter corsFilter() {
		// 1.添加CORS配置信息
		CorsConfiguration config = new CorsConfiguration();
		// 放行哪些原始域
		config.addAllowedOriginPattern("*");
		// 是否发送Cookie信息
		config.setAllowCredentials(true);
		// 放行哪些原始域(请求方式)
		config.addAllowedMethod("*");
		// 放行哪些原始域(头部信息)
		config.addAllowedHeader("*");
		// 暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
		config.addExposedHeader(HttpHeaders.LOCATION);
		config.setExposedHeaders(Arrays.asList("JSESSIONID", "SESSION", "token", HttpHeaders.LOCATION,
				HttpHeaders.ACCEPT, HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS,
				HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, HttpHeaders.COOKIE, HttpHeaders.SET_COOKIE,
				HttpHeaders.SET_COOKIE2));
		// 2.添加映射路径
		UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
		configSource.registerCorsConfiguration("/**", config);
		log.info("CorsFilter init end。。。。");
		// 3.返回新的CorsFilter.
		return new CorsFilter(configSource);
	}



### Spring Security 6.x 中的 CORS 配置教程与最佳实践 #### 启用 CORS 支持 为了启用源资源共享(CORS),可以在应用程序的安全配置类中通过覆盖`configure(HttpSecurity http)`方法来设置CORS策略。这可以通过调用`.cors()`并提供具体的配置选项来完成[^1]。 ```java @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() .csrf().disable() // 如果不需要CSRF保护可以禁用它 ... } } ``` #### 自定义 CORS 过滤器 如果默认的行为不满足需求,则可以选择创建一个自定义过滤器,并将其注册到安全链中: ```java @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://example.com")); configuration.setAllowCredentials(true); configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "OPTIONS")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(new CorsFilter(corsConfigurationSource()), ChannelProcessingFilter.class) ... ; } ``` #### 使用全局属性简化配置 对于简单的场景,也可以利用Spring Boot 的全局属性来进行基本的CORS配置而无需编写额外Java代码,在application.properties 或 application.yml 文件里添加如下内容即可生效: ```properties # application.properties spring.mvc.cors.allowed-origins=http://localhost:8080 spring.mvc.cors.allowed-methods=GET, POST, PUT, DELETE, OPTIONS spring.mvc.cors.allow-credentials=true ``` 或者YAML格式: ```yaml # application.yml spring: mvc: cors: allowed-origins: 'http://localhost:8080' allowed-methods: GET, POST, PUT, DELETE, OPTIONS allow-credentials: true ``` 以上方式适用于大多数情况下的简单应用部署环境;但对于更复杂的应用程序来说,建议采用编程的方式进行细粒度控制以确保安全性[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值