@CrossOrigin
注解
如果想要对某一接口配置 CORS
,可以在方法上添加 @CrossOrigin
注解 :
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String greetings() {
return "{"project":"just a test"}";
}
如果想对一系列接口添加 CORS 配置,可以在类上添加注解,对该类声明所有接口都有效:
@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RestController
@SpringBootApplication
public class SpringBootCorsTestApplication {
}
全局配置类
由于WebMvcConfigurerAdapter
类被弃用,新的实现是:
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
//省略
}
@Configuration
public class WebMvcConfg extends WebMvcConfigurationSupport {
//省略
}
所以配置类可以这样写:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost.com")
.allowedMethods("GET", "POST")
.allowedHeaders()
.allowCredentials(true);
}
}
也可以这样写:
@Configuration
public class WebMvcConfig {
@Bean
public WebMvcConfigurationSupport corsBeanConfigurer() {
return new WebMvcConfigurationSupport() {
@Override
protected void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders()
.allowCredentials(true);
}
};
}
}
过滤器
过滤器添加头
@Configuration
public class MyConfiguration {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://domain1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}