1.yml中配置参数
cors:
origins: [http://localhost:8087]
credentials: true
methods: [GET,POST,PUT,DELET,OPTIONS]
heads: []
exposeHeaders: [user_token]
2.properties对象
@Configuration
@ConfigurationProperties(prefix = "cors")
public class CorsProperties {
private List<String> origins;
private Boolean credentials;
private List<String> methods;
private List<String> heads;
private List<String> exposeHeaders;
}
3.注册bean
@Configuration
public class CorsConfig {
@Resource
private CorsProperties corsProperties;
@Bean
public FilterRegistrationBean cors() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(corsProperties.getOrigins());
config.setAllowCredentials(corsProperties.getCredentials());
if (corsProperties.getMethods().size() == 0 || corsProperties.getMethods() == null)
config.addAllowedMethod("*");
else
config.setAllowedMethods(corsProperties.getMethods());
if (corsProperties.getHeads().size() == 0 || corsProperties.getHeads() == null)
config.addAllowedHeader("*");
else
config.setAllowedHeaders(corsProperties.getHeads());
if (corsProperties.getExposeHeaders().size() > 0 || corsProperties.getExposeHeaders() != null)
config.setExposedHeaders(corsProperties.getHeads());
source.registerCorsConfiguration("/**", config);
CorsFilter corsFilter = new CorsFilter(source);
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(corsFilter);
filterRegistrationBean.setOrder(0);
return filterRegistrationBean;
}
}