1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.bremersee.web.servlet;
18
19 import lombok.extern.slf4j.Slf4j;
20 import org.bremersee.web.CorsProperties;
21 import org.bremersee.web.CorsProperties.CorsConfiguration;
22 import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
23 import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type;
24 import org.springframework.boot.context.event.ApplicationReadyEvent;
25 import org.springframework.boot.context.properties.EnableConfigurationProperties;
26 import org.springframework.context.annotation.Configuration;
27 import org.springframework.context.event.EventListener;
28 import org.springframework.lang.NonNull;
29 import org.springframework.util.ClassUtils;
30 import org.springframework.web.servlet.config.annotation.CorsRegistry;
31 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
32
33
34
35
36
37
38 @ConditionalOnWebApplication(type = Type.SERVLET)
39 @EnableConfigurationProperties(CorsProperties.class)
40 @Configuration
41 @Slf4j
42 public class CorsAutoConfiguration implements WebMvcConfigurer {
43
44 private final CorsProperties properties;
45
46
47
48
49
50
51 public CorsAutoConfiguration(CorsProperties properties) {
52 this.properties = properties;
53 }
54
55
56
57
58 @EventListener(ApplicationReadyEvent.class)
59 public void init() {
60 log.info("\n"
61 + "*********************************************************************************\n"
62 + "* {}\n"
63 + "*********************************************************************************\n"
64 + "* properties = {}\n"
65 + "*********************************************************************************",
66 ClassUtils.getUserClass(getClass()).getSimpleName(), properties);
67 }
68
69 @SuppressWarnings("DuplicatedCode")
70 @Override
71 public void addCorsMappings(@NonNull CorsRegistry corsRegistry) {
72 if (!properties.isEnable()) {
73 return;
74 }
75 for (CorsConfiguration config : properties.getConfigs()) {
76 corsRegistry.addMapping(config.getPathPattern())
77 .allowedOrigins(config.getAllowedOrigins().toArray(new String[0]))
78 .allowedMethods(config.getAllowedMethods().toArray(new String[0]))
79 .allowedHeaders(config.getAllowedHeaders().toArray(new String[0]))
80 .exposedHeaders(config.getExposedHeaders().toArray(new String[0]))
81 .maxAge(config.getMaxAge())
82 .allowCredentials(config.isAllowCredentials());
83 }
84 }
85
86 }