13
13
package com .tinyengine .it .config .filter ;
14
14
15
15
import org .springframework .beans .factory .annotation .Value ;
16
+ import org .springframework .context .annotation .Bean ;
16
17
import 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 ;
18
21
import org .springframework .web .servlet .config .annotation .WebMvcConfigurer ;
19
22
23
+ import java .util .Arrays ;
24
+ import java .util .List ;
25
+
20
26
@ Configuration
21
27
public class WebConfig implements WebMvcConfigurer {
22
28
@ Value ("${cors.allowed-origins}" )
23
29
private String allowedOrigins ;
24
30
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