跨域问题在web开发中最常见的问题之一,解决方式可以是从前端入手也可以是服务器端处理,今天先说一下后端的处理方式之一,其他方式希望大家提供:
使用springboot开发,通过继承DefaultCorsProcessor过滤放行的域名
代码如下:
public class CorsProcessor extends DefaultCorsProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(CorsProcessor.class);
/**
* Check the origin and determine the origin for the response. The default
* implementation simply delegates to
* {@link org.springframework.web.cors.CorsConfiguration#checkOrigin(String)}.
*/
@Override
protected String checkOrigin(CorsConfiguration config, String requestOrigin) {
//需要放行的域名
try {
if (requestOrigin != null) {
URI uri = new URI(requestOrigin);
if (uri.getHost().endsWith(".xx.com")) {
LOGGER.debug("跨域处理器放行Origin:{}", requestOrigin);
return requestOrigin;
}
}
} catch (URISyntaxException e) {
LOGGER.error("跨域转换错误",e);
}
return super.checkOrigin(config, requestOrigin);
}
}
启动Bean中增加
@Configuration
public class FilterConfiguration {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
CorsFilter corsFilter = new CorsFilter(source);
corsFilter.setCorsProcessor(new CorsProcessor());
FilterRegistrationBean bean = new FilterRegistrationBean(corsFilter);
bean.setOrder(1);
return bean;
}
}