關于springboot2.4跨域配置問題
更新時間:2021年07月22日 14:17:30 作者:似水已流年
這篇文章主要介紹了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、但是實際開發(fā)中我們需要結合,spring-security、oauth2等等,就會發(fā)現上面的配置失效了,那是因為前面的Filter優(yōu)先級太高了,那我們可以采取如下配置
``` 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)); //這里設置優(yōu)先級最高 bean.setOrder(Ordered.HIGHEST_PRECEDENCE); return bean; } }
到此這篇關于springboot2.4跨域配置的文章就介紹到這了,更多相關springboot跨域配置內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!