跨域配置

This commit is contained in:
lxp
2026-10-14 10:49:13 +08:00
parent 9754a5d818
commit ef80cebb73
13 changed files with 272 additions and 1 deletions
@@ -0,0 +1,8 @@
package com.linkerbot.cadworld.config;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "app.admin.cors")
public record AdminCorsProperties(List<String> allowedOrigins) {
}
@@ -1,15 +1,39 @@
package com.linkerbot.cadworld.config;
import com.linkerbot.cadworld.audit.OperationAuditInterceptor;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Slf4j
@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
private final OperationAuditInterceptor audit;
private final AdminCorsProperties cors;
@Override
public void addCorsMappings(CorsRegistry registry) {
List<String> origins = cors.allowedOrigins();
if (origins == null || origins.isEmpty()) return;
String[] allowed = origins.stream().map(String::trim).filter((String origin) -> !origin.isBlank()).toArray(String[]::new);
if (allowed.length == 0) return;
for (String origin : allowed) {
if (origin.contains("*")) throw new IllegalArgumentException("管理接口凭证跨域必须配置具体前端域名");
}
registry.addMapping("/admin-api/**")
.allowedOrigins(allowed)
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("Content-Type", "Authorization", "X-Request-Id")
.exposedHeaders("X-Request-Id")
.allowCredentials(true)
.maxAge(3600);
log.info("管理接口跨域配置已启用 path=/admin-api/** allowedOrigins={}", List.of(allowed));
}
@Override
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(audit).addPathPatterns("/admin-api/**"); }
@@ -8,6 +8,9 @@ spring:
maximum-pool-size: 20
app:
admin:
cors:
allowed-origins: ${APP_ADMIN_ALLOWED_ORIGINS:https://cadworld-admin.robotquan.com}
storage:
root-prefix: ${OSS_ROOT_PREFIX:cadworld}
@@ -11,6 +11,10 @@ spring:
connection-timeout: 5000
app:
admin:
cors:
# Origin 必须包含协议;可用逗号分隔的完整来源覆盖。
allowed-origins: ${APP_ADMIN_ALLOWED_ORIGINS:https://dev-cadworld-admin.robotquan.com}
storage:
root-prefix: ${OSS_ROOT_PREFIX:cadworld_dev}
@@ -35,6 +35,8 @@ springdoc:
app:
admin:
cors:
allowed-origins: ${APP_ADMIN_ALLOWED_ORIGINS:}
operator:
id: ${APP_ADMIN_OPERATOR_ID:0}
name: ${APP_ADMIN_OPERATOR_NAME:TEST_OPERATOR}
@@ -0,0 +1,116 @@
package com.linkerbot.cadworld.config;
import com.linkerbot.cadworld.audit.OperationAuditInterceptor;
import com.linkerbot.cadworld.common.web.RequestIdFilter;
import com.linkerbot.cadworld.service.AdminOperatorProvider;
import com.linkerbot.cadworld.service.OperationLogService;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.http.HttpHeaders;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class AdminCorsConfigurationTest {
private final WebApplicationContextRunner runner = new WebApplicationContextRunner()
.withInitializer(context -> context.getEnvironment().getPropertySources()
.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME))
.withInitializer(new ConfigDataApplicationContextInitializer())
.withUserConfiguration(CorsTestConfiguration.class);
@ParameterizedTest
@CsvSource({
"test, https://dev-cadworld-admin.robotquan.com, https://cadworld-admin.robotquan.com",
"prod, https://cadworld-admin.robotquan.com, https://dev-cadworld-admin.robotquan.com"
})
void profileAllowsItsFrontendAndRejectsOtherOrigins(String profile, String allowedOrigin, String otherOrigin) {
runner.withPropertyValues("spring.profiles.active=" + profile).run(context -> {
assertThat(context).hasNotFailed();
MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(new RequestIdFilter()).build();
for (String method : List.of("GET", "HEAD", "POST", "PUT", "DELETE")) {
mvc.perform(options("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, allowedOrigin)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, method)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "content-type,authorization,x-request-id"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigin))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600"));
}
mvc.perform(get("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, allowedOrigin)
.header("X-Request-Id", "cors-test"))
.andExpect(status().isOk()).andExpect(content().string("ok"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigin))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "X-Request-Id"))
.andExpect(header().string("X-Request-Id", "cors-test"));
for (String origin : List.of(otherOrigin, allowedOrigin.replace("https://", "http://"), "https://untrusted.example")) {
mvc.perform(options("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, origin)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PUT"))
.andExpect(status().isForbidden())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
mvc.perform(get("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, origin))
.andExpect(status().isForbidden());
}
});
}
@Test
void environmentVariableCanOverrideWhitelistWithMultipleOrigins() {
runner.withPropertyValues("spring.profiles.active=test",
"APP_ADMIN_ALLOWED_ORIGINS=http://localhost:5173,https://custom.example").run(context -> {
assertThat(context).hasNotFailed();
MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build();
for (String origin : List.of("http://localhost:5173", "https://custom.example")) {
mvc.perform(get("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, origin))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin));
}
mvc.perform(get("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, "https://dev-cadworld-admin.robotquan.com"))
.andExpect(status().isForbidden());
});
}
@Test
void credentialedCorsRejectsWildcardAtStartup() {
runner.withPropertyValues("spring.profiles.active=test", "APP_ADMIN_ALLOWED_ORIGINS=*")
.run(context -> assertThat(context.getStartupFailure()).hasRootCauseInstanceOf(IllegalArgumentException.class));
}
@TestConfiguration(proxyBeanMethods = false)
@EnableWebMvc
@EnableConfigurationProperties(AdminCorsProperties.class)
@Import(WebConfig.class)
static class CorsTestConfiguration {
@Bean OperationAuditInterceptor audit() {
return new OperationAuditInterceptor(mock(OperationLogService.class), mock(AdminOperatorProvider.class));
}
@Bean ProbeController probeController() { return new ProbeController(); }
}
@RestController
static class ProbeController {
@RequestMapping(value = "/admin-api/cors-probe", method = {
RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE
})
public String probe() { return "ok"; }
}
}