Skip to content

Commit c7f29d2

Browse files
committed
feat(cors): 添加跨域配置支持
从配置文件动态加载跨域设置,包括允许的源、方法、头部和凭证。增强灵活性和可维护性
1 parent 090392f commit c7f29d2

3 files changed

Lines changed: 82 additions & 25 deletions

File tree

backend/config.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,10 @@ max_connections = 5
1212
[jwt]
1313
secret = "your_secret_key_change_this_in_production"
1414
expiration = 1140 # 过期时间(分钟)
15+
16+
#跨域配置
17+
[cors]
18+
allowed_origins = ["http://localhost:4321", "https://blog.exquisitecore.xyz"]
19+
allowed_methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
20+
allowed_headers = ["Authorization", "Content-Type"]
21+
allow_credentials = true

backend/src/config.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ pub struct Config {
2424
pub server: ServerConfig,
2525
pub database: DatabaseConfig,
2626
pub jwt: JwtConfig,
27+
pub cors: CorsConfig,
2728
}
2829

2930
#[derive(Debug, Serialize, Deserialize, Clone)]
@@ -44,6 +45,14 @@ pub struct JwtConfig {
4445
pub expiration: u64, // 过期时间(分钟)
4546
}
4647

48+
#[derive(Debug, Serialize, Deserialize, Clone)]
49+
pub struct CorsConfig {
50+
pub allowed_origins: Vec<String>,
51+
pub allowed_methods: Vec<String>,
52+
pub allowed_headers: Vec<String>,
53+
pub allow_credentials: bool,
54+
}
55+
4756
impl Config {
4857
#[allow(dead_code)]
4958
pub fn new() -> Self {
@@ -72,6 +81,18 @@ impl Config {
7281
secret: "default_secret_key_change_in_production".to_string(),
7382
expiration: 60, // 60分钟
7483
},
84+
cors: CorsConfig {
85+
allowed_origins: vec!["http://localhost:4321".to_string()],
86+
allowed_methods: vec![
87+
"GET".to_string(),
88+
"POST".to_string(),
89+
"PUT".to_string(),
90+
"DELETE".to_string(),
91+
"OPTIONS".to_string(),
92+
],
93+
allowed_headers: vec!["Authorization".to_string(), "Content-Type".to_string()],
94+
allow_credentials: true,
95+
},
7596
}
7697
}
7798
}

backend/src/middleware/cors.rs

Lines changed: 54 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,60 @@
1+
use crate::config::get_config;
12
use axum::http;
3+
use http::HeaderName;
24
use http::Method;
3-
use http::header::{AUTHORIZATION, CONTENT_TYPE};
4-
use tower_http::cors::CorsLayer;
5+
use tower_http::cors::{Any, CorsLayer};
56

67
/// 创建跨域中间件
78
pub fn create_layer() -> CorsLayer {
8-
// 定义允许的源
9-
let origins = [
10-
"http://localhost:4321".parse().unwrap(),
11-
"https://blog.exquisitecore.xyz".parse().unwrap(),
12-
];
13-
14-
// 定义允许的方法
15-
let methods = [
16-
Method::GET,
17-
Method::POST,
18-
Method::PUT,
19-
Method::DELETE,
20-
Method::OPTIONS,
21-
];
22-
23-
// 定义允许的头部
24-
let headers = [AUTHORIZATION, CONTENT_TYPE];
25-
26-
CorsLayer::new()
27-
.allow_methods(methods)
28-
.allow_headers(headers)
29-
.allow_origin(origins)
30-
.allow_credentials(true)
9+
let config = get_config();
10+
let cors_config = &config.cors;
11+
12+
// 从配置中获取允许的源
13+
let origins = cors_config
14+
.allowed_origins
15+
.iter()
16+
.filter_map(|origin| origin.parse().ok())
17+
.collect::<Vec<_>>();
18+
19+
// 从配置中获取允许的方法
20+
let methods = cors_config
21+
.allowed_methods
22+
.iter()
23+
.filter_map(|method| method.parse::<Method>().ok())
24+
.collect::<Vec<_>>();
25+
26+
// 从配置中获取允许的头部
27+
let headers = cors_config
28+
.allowed_headers
29+
.iter()
30+
.filter_map(|header| header.parse::<HeaderName>().ok())
31+
.collect::<Vec<_>>();
32+
33+
let mut layer = CorsLayer::new();
34+
35+
// 如果有配置的源,则使用它们,否则允许任何源
36+
if !origins.is_empty() {
37+
layer = layer.allow_origin(origins);
38+
} else {
39+
layer = layer.allow_origin(Any);
40+
}
41+
42+
// 如果有配置的方法,则使用它们,否则允许任何方法
43+
if !methods.is_empty() {
44+
layer = layer.allow_methods(methods);
45+
} else {
46+
layer = layer.allow_methods(Any);
47+
}
48+
49+
// 如果有配置的头部,则使用它们,否则允许任何头部
50+
if !headers.is_empty() {
51+
layer = layer.allow_headers(headers);
52+
} else {
53+
layer = layer.allow_headers(Any);
54+
}
55+
56+
// 设置是否允许凭证
57+
layer = layer.allow_credentials(cors_config.allow_credentials);
58+
59+
layer
3160
}

0 commit comments

Comments
 (0)