Код: Выделить всё
org.springframework.boot
spring-boot-starter-parent
3.3.5
17
org.springframework.boot
spring-boot-starter-web
org.springframework.security
spring-security-test
test
Код: Выделить всё
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("http://localhost", //
"https://test.example.org/", //
"https://stage.example.org", //
"https://example.org"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
configuration.setAllowedHeaders(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return new CorsFilter(source);
}
}
Код: Выделить всё
$ curl -v -H "Access-Control-Request-Method: GET" -H "Origin: https://www.example.com"
http://localhost:8080/my-api/my-endpoint
Код: Выделить всё
$ curl -v -H "Access-Control-Request-Method: GET" -H "Origin: http://localhost"
http://localhost:8080/my-api/my-endpoint
Однако этот тест JUnit не пройден:
Код: Выделить всё
@Test
void corsDeniesExampleDotCom() throws Exception {
MvcResult result = mockMvc.perform(get("/my-endpoint") //
.header("Access-Control-Request-Method", "GET") //
.header("Origin", "http://example.com")) //
.andExpect(status().isForbidden()) //
.andDo(print()) //
.andReturn();
}
Status expected: but was:
Примечания:
Я просмотрел тестирование COR в SpringBootTest, и это старая версия вопрос, а предоставленные ответы не работают.
Подробнее здесь: https://stackoverflow.com/questions/792 ... curl-works