Springboot升级至2.4.0中出现的跨域问题,分析以及修改

Spring Boot 2.4.0 升级跨域问题分析与解决
博客聚焦Spring Boot升级至2.4.0出现的跨域问题。对比2.3.5.RELEASE与2.4.0版本对应Spring版本,分析2.3.5.RELEASE设置跨域代码,深入剖析5.3.x源码中CorsFilter等方法。指出2.4.0版本按原设置访问API会报错,并给出两种修改方式。

问题

Springboot升级至2.4.0中出现的跨域问题。
在Springboot 2.4.0版本之前使用的是2.3.5.RELEASE,对应的Spring版本为5.2.10.RELEASE。
升级至2.4.0后,对应的Spring版本为5.3.1。
Springboot2.3.5.RELEASE时,我们可以使用CorsFilter设置跨域。

分析

版本2.3.5.RELEASE 设置跨域

设置代码如下:

@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
   
   
    @Bean
    public CorsFilter corsFilter() {
   
   
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 允许访问的客户端域名
        config.addAllowedOrigin("*");
        // 允许服务端访问的客户端请求头
        config.addAllowedHeader("*");
        // 允许访问的方法名,GET POST等
        config.addAllowedMethod("*");
        // 对接口配置跨域设置
        source.registerCorsConfiguration("/**" , config);
        return new CorsFilter(source);
    }
}

是允许使用*设置允许的Origin。
这里我们看一下类CorsFilter的源码,5.3.x版本开始,针对CorsConfiguration新增了校验

5.3.x源码分析

CorsFilter

/**
 * {@link javax.servlet.Filter} to handle CORS pre-flight requests and intercept
 * CORS simple and actual requests with a {@link CorsProcessor}, and to update
 * the response, e.g. with CORS response headers, based on the policy matched
 * through the provided {@link CorsConfigurationSource}.
 *
 * <p>This is an alternative to configuring CORS in the Spring MVC Java config
 * and the Spring MVC XML namespace. It is useful for applications depending
 * only on spring-web (not on spring-webmvc) or for security constraints that
 * require CORS checks to be performed at {@link javax.servlet.Filter} level.
 *
 * <p>This filter could be used in conjunction with {@link DelegatingFilterProxy}
 * in order to help with its initialization.
 *
 * @author Sebastien Deleuze
 * @since 4.2
 * @see <a href="https://www.w3.org/TR/cors/">CORS W3C recommendation</a>
 * @see UrlBasedCorsConfigurationSource
 */
public class CorsFilter extends OncePerRequestFilter {
   
   

	private final CorsConfigurationSource configSource;

	private CorsProcessor processor = new DefaultCorsProcessor();


	/**
	 * Constructor accepting a {@link CorsConfigurationSource} used by the filter
	 * to find the {@link CorsConfiguration} to use for each incoming request.
	 * @see UrlBasedCorsConfigurationSource
	 */
	public CorsFilter(CorsConfigurationSource configSource) {
   
   
		Assert.notNull(configSource, "CorsConfigurationSource must not be null");
		this.configSource = configSource;
	}


	/**
	 * Configure a custom {@link CorsProcessor} to use to apply the matched
	 * {@link CorsConfiguration} for a request.
	 * <p>By default {@link DefaultCorsProcessor} is used.
	 */
	public void setCorsProcessor(CorsProcessor processor) {
   
   
		Assert.notNull(processor, "CorsProcessor must not be null");
		this.processor = processor;
	}


	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
			FilterChain filterChain) throws ServletException, IOException {
   
   

		CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);
		boolean isValid = this.processor.processRequest(corsConfiguration, request, response);
		if (!isValid || CorsUtils.isPreFlightRequest(request
### Spring Boot集成Nacos 2.4.0作为服务注册中心和配置中心 #### 准备工作 为了在Spring Boot项目中集成Nacos 2.4.0,需先安装并启动Nacos服务器。下载地址可以从[Nacos GitHub](https://github.com/alibaba/nacos/releases/tag/2.4.0)获取。 #### 添加依赖项 编辑`pom.xml`文件来引入必要的Maven依赖: ```xml <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>nacos-discovery-spring-boot-starter</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>nacos-config-spring-boot-starter</artifactId> <version>2.4.0</version> </dependency> ``` 这些依赖分别用于支持服务发现和服务配置功能[^1]。 #### 应用程序属性设置 修改`application.properties`或`application.yml`以连接到本地或其他位置运行的Nacos实例: 对于`.properties`格式: ```properties spring.application.name=demo-service nacos.discovery.server-addr=127.0.0.1:8848 nacos.config.server-addr=127.0.0.1:8848 ``` 对于`.yml`格式: ```yaml spring: application: name: demo-service nacos: discovery: server-addr: 127.0.0.1:8848 config: server-addr: 127.0.0.1:8848 ``` 上述配置指定了应用程序名称以及Nacos的服务地址[^2]。 #### 启动类注解 确保主应用类上有@EnableDiscoveryClient注解以便开启服务发现特性;如果要使用Nacos配置,则无需额外操作因为starter会自动处理。 ```java import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableDiscoveryClient public class DemoApplication { public static void main(String[] args){ SpringApplication.run(DemoApplication.class,args); } } ``` 此段代码展示了如何通过简单的Java配置启用客户端发现机制[^3]。 #### 测试验证 编写单元测试或者创建RESTful接口调用来确认服务已成功注册至Nacos,并能正常拉取远程配置信息。 ---
评论 7
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

向往的生活Life

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值