1313package com .tinyengine .it .config .filter ;
1414
1515import org .springframework .beans .factory .annotation .Value ;
16+ import org .springframework .context .annotation .Bean ;
1617import org .springframework .context .annotation .Configuration ;
17- import org .springframework .web .servlet .config .annotation .CorsRegistry ;
18+ import org .springframework .web .cors .CorsConfiguration ;
19+ import org .springframework .web .cors .UrlBasedCorsConfigurationSource ;
20+ import org .springframework .web .filter .CorsFilter ;
1821import org .springframework .web .servlet .config .annotation .WebMvcConfigurer ;
1922
23+ import java .util .Arrays ;
24+ import java .util .List ;
25+
2026@ Configuration
2127public class WebConfig implements WebMvcConfigurer {
2228 @ Value ("${cors.allowed-origins}" )
2329 private String allowedOrigins ;
2430
25- @ Value ("${cors.allowed-methods}" )
26- private String allowedMethods ;
27-
28- @ Value ("${cors.allowed-headers}" )
29- private String allowedHeaders ;
30-
31- @ Value ("${cors.exposed-headers}" )
32- private String exposedHeaders ;
33-
34- @ Value ("${cors.allow-credentials}" )
35- private boolean allowCredentials ;
36-
37-
38- @ Override
39- public void addCorsMappings (CorsRegistry registry ) {
40- // 配置 CORS
41- registry .addMapping ("/**" ) // 允许所有路径
42- .allowedOrigins (allowedOrigins ) // 允许特定来源的前端地址
43- .allowedMethods (allowedMethods .split ("," )) // 允许的 HTTP 方法
44- .allowedHeaders (allowedHeaders .split ("," )) // 允许的请求头
45- .exposedHeaders (exposedHeaders .split ("," )) // 暴露给前端的响应头
46- .allowCredentials (allowCredentials ); // 允许携带凭证
47- }
48- }
31+ @ Bean
32+ public CorsFilter corsFilter ()
33+ {
34+ // 跨域配置地址
35+ List <String > crosDomainList = Arrays .asList (allowedOrigins .split ("," ));
36+
37+ CorsConfiguration corsConfiguration = new CorsConfiguration ();
38+ // 1、允许来源
39+ corsConfiguration .setAllowedOriginPatterns (crosDomainList );
40+ // 2、允许任何请求头
41+ corsConfiguration .addAllowedHeader (CorsConfiguration .ALL );
42+ // 3、允许任何方法
43+ corsConfiguration .addAllowedMethod (CorsConfiguration .ALL );
44+ // 4、允许凭证
45+ corsConfiguration .setAllowCredentials (true );
46+
47+ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource ();
48+ source .registerCorsConfiguration ("/**" , corsConfiguration );
49+ return new CorsFilter (source );
50+ }
51+
52+ }
0 commit comments