springboot2.4跨域配置的方法

Crq
Crq
管理员
1864
文章
0
粉丝
Linux教程评论484字数 236阅读0分47秒阅读模式
摘要这篇文章主要介绍了springboot2.4跨域配置的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

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;
}
}

到此这篇关于springboot2.4跨域配置的文章就介绍到这了

weinxin
我的微信
微信号已复制
我的微信
这是我的微信扫一扫
 
Crq
  • 本文由 Crq 发表于2021年8月5日 19:50:58
  • 转载请注明:https://www.cncrq.com/9986.html
【技术快报】9.19-9.25 Linux教程

【技术快报】9.19-9.25

本期《linux就该这么学》的技术周报中,将为您推出最牛X的GCC 内联汇编、Inxi:获取Linux系统和硬件信息的神器、使用 Github Pages 发布你的项目文档、5分钟...
Linux文件读写机制及优化方式 Linux教程

Linux文件读写机制及优化方式

Linux是一个可控性强的,安全高效的操作系统。本文只讨论Linux下文件的读写机制,不涉及不同读取方式如read,fread,cin等的对比,这些读取方式本质上都是调用系统api...
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定

拖动滑块以完成验证