【发布时间】:2017-07-24 03:25:37
【问题描述】:
我正在尝试编写一个测试来验证我们的 CORS 设置。我像这样配置CORS。
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
// super.configure(httpSecurity);
httpSecurity.csrf().disable();
httpSecurity.authorizeRequests().antMatchers("/**").permitAll();
httpSecurity.cors();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
List<String> allowedMethods = CORS_ALLOWED_METHODS;
configuration.setAllowedMethods(allowedMethods);
configuration.setAllowedOrigins(CORS_ALLOWED_ORIGINS);
configuration.setAllowedHeaders(CORS_ALLOWED_HEADERS);
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
我已通过调试器验证CORS_ALLOWED_METHODS 在我的测试运行时具有值。
这是我的测试。当我在标题上断言时它失败了。
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("dev")
public class ControllerTests {
@Autowired
private WebApplicationContext wac;
public MockMvc mockMvc;
@Before
public void setup() {
DefaultMockMvcBuilder builder = MockMvcBuilders
.webAppContextSetup(this.wac)
.apply(SecurityMockMvcConfigurers.springSecurity())
.dispatchOptions(true);
this.mockMvc = builder.build();
}
@Test
public void testCors() throws Exception {
this.mockMvc
.perform(get("/test-cors"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(header().string("Access-Control-Allow-Methods", "OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT"))
.andExpect(content().string("whatever"));
}
@SpringBootApplication(scanBasePackages = {"the.packages"})
@Controller
static class TestApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(TestApplication.class, args);
}
@RequestMapping(value = {"test-cors"}, method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody String testCors() {
return "whatever";
}
}
}
请注意,当我使用此配置实际运行 SpringBoot 应用程序时,我们确实会获得 CORS 标头。
任何帮助表示赞赏。
【问题讨论】:
-
我认为您应该在创建模拟 GET 请求时将 http
Origin标头添加到要测试的值中。我怀疑 Spring 不会处理您对没有来源的 CORS 的请求。 -
是的,我今天早上知道了。如果你把它写成答案我会接受。
标签: spring-mvc spring-boot testing cors