优化:优化跨域配置,可支持配置允许跨域的具体域名或 *

This commit is contained in:
Charles7c 2023-03-23 19:54:15 +08:00
parent 30ba5bb5f4
commit 8591a24730
3 changed files with 14 additions and 8 deletions

View File

@ -36,6 +36,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.charles7c.cnadmin.common.config.properties.CorsProperties;
import top.charles7c.cnadmin.common.config.properties.LocalStorageProperties;
import top.charles7c.cnadmin.common.constant.StringConsts;
/**
* Web MVC 配置
@ -75,13 +76,17 @@ public class WebMvcConfiguration implements WebMvcConfigurer {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// 配置为 true 后则必须配置允许跨域的域名且不允许配置为 *
config.setAllowCredentials(true);
// 设置跨域允许时间
config.setMaxAge(1800L);
// 配置允许跨域的域名
corsProperties.getAllowedOrigins().forEach(config::addAllowedOrigin);
if (corsProperties.getAllowedOrigins().contains(StringConsts.ASTERISK)) {
config.addAllowedOriginPattern(StringConsts.ASTERISK);
} else {
// 配置为 true 后则必须配置允许跨域的域名且不允许配置为 *
config.setAllowCredentials(true);
corsProperties.getAllowedOrigins().forEach(config::addAllowedOrigin);
}
// 配置允许跨域的请求方式
corsProperties.getAllowedMethods().forEach(config::addAllowedMethod);
// 配置允许跨域的请求头

View File

@ -40,6 +40,11 @@ public class StringConsts implements StrPool {
*/
public static final String SEMICOLON = ";";
/**
* 星号
*/
public static final String ASTERISK = "*";
/**
* 中文逗号
*/

View File

@ -176,11 +176,7 @@ local-storage:
--- ### 跨域配置
cors:
# 配置允许跨域的域名
allowedOrigins:
- http://127.0.0.1:5173
- http://localhost:5173
- http://cnadmin.charles7c.top
- https://cnadmin.charles7c.top
allowedOrigins: '*'
# 配置允许跨域的请求方式
allowedMethods: '*'
# 配置允许跨域的请求头