Spring boot https 跨域问题
@Configuration
public class CorsConfigures implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 用户证书验证,
registry.addMapping("/**").allowedOrigins("*").allowedMethods("POST", "GET", "DELETE", "PUT", "HEAD", "OPTIONS")
.allowCredentials(false)
.allowedHeaders(
"Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Pragma")
.exposedHeaders(
"Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Allow-Credentials,Pragma")
// 最大过期时间
.maxAge(3600);
}@Bean
public FilterRegistrationBean corsFilter() {
System.out.println("join configur");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// 设置你要允许的网站域名,如果全允许则设为 *
config.addAllowedOrigin("*");
// 如果要限制 HEADER 或 METHOD 请自行更改
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
// 这个顺序很重要哦,为避免麻烦请设置在最前
bean.setOrder(0);
return bean;
}
1.allowCredentials() 方法:
/**
* Whether the browser should send credentials, such as cookies along with
* cross domain requests, to the annotated endpoint. The configured value is
* set on the {@code Access-Control-Allow-Credentials} response header of
* preflight requests.
* <p><strong>NOTE:</strong> Be aware that this option establishes a high
* level of trust with the configured domains and also increases the surface
* attack of the web application by exposing sensitive user-specific
* information such as cookies and CSRF tokens.
* <p>By default this is not set in which case the
* {@code Access-Control-Allow-Credentials} header is also not set and
* credentials are therefore not allowed.
*/
public CorsRegistration allowCredentials(boolean allowCredentials) {
this.config.setAllowCredentials(allowCredentials);
return this;
}源码说这个方法是用户证书验证,之前遇到过一个问题 就是自己配置的证书,然后这里设置了true,游览器就会验证
google 游览器发送请求被拦截了,比如像火狐、IE之类可以添加例外的 就没这么严格
所以如果自己配置证书的话 这里设置为false