Skip to content

Commit ad2b719

Browse files
committed
feat(cors): 支持通配符和多源CORS配置
- 添加对 "*" 通配符的支持,发送通配符响应头 - 支持逗号分隔的多个源配置 - 保留对本地地址的默认支持 - 维持现有HTTP方法和头部配置 - 保持凭证支持和最大年龄设置
1 parent 484b297 commit ad2b719

1 file changed

Lines changed: 33 additions & 12 deletions

File tree

  • file_classification_webapi/src/bin/utils

file_classification_webapi/src/bin/utils/cors.rs

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,39 @@ pub fn create_cors() -> Cors {
2222

2323
if cors_enabled {
2424
log::info!("CORS 已启用,允许来源: {}", cors_origin);
25-
Cors::default()
26-
.allowed_origin(&cors_origin)
27-
.allowed_origin(&format!("http://127.0.0.1:{}", port))
28-
.allowed_origin(&format!("http://localhost:{}", port))
29-
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
30-
.allowed_headers(vec![
31-
actix_web::http::header::AUTHORIZATION,
32-
actix_web::http::header::ACCEPT,
33-
actix_web::http::header::CONTENT_TYPE,
34-
])
35-
.supports_credentials()
36-
.max_age(3600)
25+
26+
// 如果 cors_origin 是 "*",则发送通配符响应头而不是在 allowed_origin 中使用 "*"
27+
if cors_origin == "*" {
28+
Cors::default()
29+
.send_wildcard()
30+
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
31+
.allowed_headers(vec![
32+
actix_web::http::header::AUTHORIZATION,
33+
actix_web::http::header::ACCEPT,
34+
actix_web::http::header::CONTENT_TYPE,
35+
])
36+
.supports_credentials()
37+
.max_age(3600)
38+
} else {
39+
// 支持逗号分隔的多个源
40+
let origins: Vec<&str> = cors_origin.split(',').map(|s| s.trim()).collect();
41+
let mut cors = Cors::default();
42+
43+
for origin in origins {
44+
cors = cors.allowed_origin(origin);
45+
}
46+
47+
cors.allowed_origin(&format!("http://127.0.0.1:{}", port))
48+
.allowed_origin(&format!("http://localhost:{}", port))
49+
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
50+
.allowed_headers(vec![
51+
actix_web::http::header::AUTHORIZATION,
52+
actix_web::http::header::ACCEPT,
53+
actix_web::http::header::CONTENT_TYPE,
54+
])
55+
.supports_credentials()
56+
.max_age(3600)
57+
}
3758
} else {
3859
log::info!("CORS 已禁用,允许所有来源");
3960
Cors::default()

0 commit comments

Comments
 (0)