ink.huaxun.gateway.config.CorsConfig Maven / Gradle / Ivy
The newest version!
package ink.huaxun.gateway.config;
import ink.huaxun.util.PlatformUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @author zhaogang
* @description 实现基本的跨域请求
* @date 2023/2/7 16:03
*/
@Configuration
public class CorsConfig {
/**
* token的头
*/
@Value("${token.header}")
private String header;
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 只有在开发环境下,才会开放跨域
if (PlatformUtil.server()) {
return new CorsFilter(source);
}
final CorsConfiguration config = new CorsConfiguration();
// 是否允许请求带有验证信息
config.setAllowCredentials(true);
// 允许访问的客户端域名
config.addAllowedOriginPattern("*");
// 允许服务端访问的客户端请求头
config.addAllowedHeader("*");
// 允许访问的方法名,GET POST等
config.addAllowedMethod("*");
// 允许公开访问的header
config.addExposedHeader(header);
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}