共计 1712 个字符,预计需要花费 5 分钟才能阅读完成。
导读 | 这篇文章主要介绍了 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 | |
*/ | |
public class WebConfig implements WebMvcConfigurer { | |
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 | |
*/ | |
public class CrosConfig { | |
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 跨域配置的文章就介绍到这了
正文完
星哥玩云-微信公众号
