springboot2.4跨域配置问题怎么解决
作者:NorthPath
时间:2023-05-11
浏览:0
1、如果只是一个简单的springbootdemo,用以下配置就行新建config类```importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.CorsRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;/***@auth
本文目录
1、如果只是一个简单的springboot demo,用以下配置就行
新建config类
```
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author yk
* @date 2021/7/19 14:36
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("*")
.maxAge(3600)
.allowCredentials(true);
}
}
```2、但是实际开发中我们需要结合,spring-security、oauth2等等,就会发现上面的配置失效了,那是因为前面的Filter优先级太高了,那我们可以采取如下配置
```
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @author yk
* @date 2021/7/19 16:21
*/
@Configuration
public class CrosConfig {
@Bean
public FilterRegistrationBean corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
//这里设置优先级最高
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}
作者最新文章
漫蛙漫画APP下载安卓版免费
2026-10-13 13:42
漫蛙动漫下载安卓版安装包
2026-10-13 13:19
漫蛙manwa2免费漫画入口在哪
2026-10-13 13:17
漫蛙2漫画入口
2026-10-13 13:03
会声会影X5去除视频原有字幕的操作方法
2026-10-13 11:07
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































