目前我只用一种方法,跨域专门用跨域过滤处理 CorsFilter 然后通过bean注入交给spring容器一并处理该过程,我们只负责进行配置即可。在这我需要讲解一下AllowCredentials 和AllowedOrigins 匹配使用 ,AllowCredentials 含义就允许携带的认证值进行访问,如果AllowedOrigins为* 全部的话,AllowCredentials 必须为false 否则无效, AllowedOrigins 指定某一些地址,AllowCredentials 则为true,
代码如下:
import org.springframework.boot.context.properties.ConfigurationProperties;
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;
import java.util.List;
@Configuration
@ConfigurationProperties(prefix = "cors")
public class CorsFilterConfig {
/**
* 源
*/
protected List<String> originUrl;
/**
* 跨域开关
*/
private String enable;
public void setEnable(String enable) {
this.enable = enable;
}
public void setOriginUrl(List<String> originUrl) {
this.originUrl = originUrl;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
CorsConfiguration configuration = new CorsConfiguration();
if ("true".equals(enable)){
/*是否允许请求带有验证信息*/
configuration.setAllowCredentials(true);
/*允许访问的客户端域名*/
configuration.setAllowedOrigins(originUrl);
}else{
/*是否允许请求带有验证信息*/
configuration.setAllowCredentials(false);
/*允许访问的客户端域名*/
configuration.addAllowedOrigin("*");
}
/*允许服务端访问的客户端请求头*/
configuration.addAllowedHeader("*");
/*允许访问的方法名,GET POST等*/
configuration.addAllowedMethod("*");
configuration.setMaxAge(3600L);
configurationSource.registerCorsConfiguration("/**", configuration);
return new CorsFilter(configurationSource);
}
}
我这中做法是方便加白名单,生产环境时我们将这个开关打开,然后配置开放对应的ip:如配置文件:
#跨域配置
cors:
enable: false
originUrl:
- http://192.168.18.165
- http://192.168.18.178:8082
- http://www.greenet.cn
- http://192.168.50.140:815
- http://192.168.50.140:820
- http://192.168.18.178:8081
- http://192.168.6.164:5500
想要对哪个ip进行开放的话就加上,然后enable 改为true,如果enable为false的话就是不受跨域限制允许所有的IP可以方法