spring cors 配置

Web 项目配置 cors 的三种方式。

Cors 属性

名称 类型 可选项 默认值 有效值 描述
allow_origins string 可选 “*” 允许跨域访问的 Origin,格式如:scheme://host:port,比如: https://blog.yl-online.top 。多个值使用 , 分割,allow_credentialfalse 时可以使用 * 来表示所有 Origin 均允许通过。你也可以在启用了 allow_credential 后使用 ** 强制允许所有 Origin 都通过,但请注意这样存在安全隐患。
allow_methods string 可选 “*” 允许跨域访问的 Method,比如: GETPOST等。多个值使用 , 分割,allow_credentialfalse 时可以使用 * 来表示所有 Origin 均允许通过。你也可以在启用了 allow_credential 后使用 ** 强制允许所有 Method 都通过,但请注意这样存在安全隐患。
allow_headers string 可选 “*” 允许跨域访问时请求方携带哪些非 CORS 规范 以外的 Header, 多个值使用 , 分割,allow_credentialfalse 时可以使用 * 来表示所有 Header 均允许通过。你也可以在启用了 allow_credential 后使用 ** 强制允许所有 Header 都通过,但请注意这样存在安全隐患。
expose_headers string 可选 “*” 允许跨域访问时响应方携带哪些非 CORS 规范 以外的 Header, 多个值使用 , 分割,allow_credentialfalse 时可以使用 * 来表示允许任意 Header 。你也可以在启用了 allow_credential 后使用 ** 强制允许任意 Header,但请注意这样存在安全隐患。
max_age integer 可选 1800 浏览器缓存 CORS 结果的最大时间,单位为秒,在这个时间范围内浏览器会复用上一次的检查结果,-1 表示不缓存。
allow_credential boolean 可选 false 是否允许跨域访问的请求方携带凭据(如 Cookie 等)。根据 CORS 规范,如果设置该选项为 true,那么将不能在其他选项中使用 *

WebMvcConfigurer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package xx.xxx;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

/**
* 如果使用 spring-security,这里配置会不生效,需要改用 CorsConfigurationSource
* 参考:https://docs.spring.io/spring-security/site/docs/current/reference/html5/#cors
*
* @param registry cors 注册器
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
/*
* When allowCredentials is true,
* allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header.
* To allow credentials to a set of origins,
* list them explicitly or consider using "allowedOriginPatterns" instead.
*/
// 是否允许跨域访问的请求方携带凭据(如 Cookie 等)。根据 CORS 规范,如果设置该选项为 true,那么将不能在其他选项中使用 *。
.allowCredentials(false)
// 开放哪些ip、端口、域名的访问权限
.allowedOrigins("*")
// .allowedOriginPatterns("*")
// "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"
.allowedMethods("*")
// 允许HTTP请求中的携带哪些Header信息
.allowedHeaders("*")
// 暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
.exposedHeaders("*");
}
}

WebSecurityConfigurerAdapter

参考:https://docs.spring.io/spring-security/site/docs/current/reference/html5/#cors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
// by default uses a Bean by the name of corsConfigurationSource
.cors(withDefaults())
...
}

/**
* 如果使用了 spring-security,cors 需要这样配置
*
* @return cors
*/
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration cfg = new CorsConfiguration();
cfg.setAllowCredentials(false);
cfg.setAllowedOrigins(Collections.singletonList("*"));
cfg.setAllowedMethods(Collections.singletonList("*"));
cfg.setAllowedHeaders(Collections.singletonList("*"));
cfg.setExposedHeaders(Collections.singletonList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", cfg);
return source;
}
}

Web Filter

如果以上两种配置方式都不生效,可以试试这种方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package xx.xxx;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
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 javax.servlet.Filter;
import java.util.Collections;

@Configuration
public class WebMvcConfig {

@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
CorsConfiguration cfg = new CorsConfiguration();
cfg.setAllowCredentials(false);
cfg.setAllowedOrigins(Collections.singletonList("*"));
cfg.setAllowedMethods(Collections.singletonList("*"));
cfg.setAllowedHeaders(Collections.singletonList("*"));
cfg.setExposedHeaders(Collections.singletonList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", cfg);
FilterRegistrationBean<CorsFilter> filter = new FilterRegistrationBean<>();
filter.setFilter(new CorsFilter(source));
filter.addUrlPatterns("/*");
filter.setOrder(0);
return filter;
}
}
  • 本文作者: forever杨
  • 本文链接: https://blog.yl-online.top/posts/210739bc.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。如果文章内容对你有用,请记录到你的笔记中。本博客站点随时会停止服务,请不要收藏、转载!