Skip to content

Commit 70bdd20

Browse files
author
tangyi
committed
<feat> 更新 MySQL 8.0 认证支持,新增认证插件配置说明,更新 README 文档,添加 cryptography 依赖,优化数据库连接错误处理
1 parent 4b573af commit 70bdd20

File tree

4 files changed

+89
-5
lines changed

4 files changed

+89
-5
lines changed

README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,45 @@ Default endpoint: http://127.0.0.1:3000/sse
150150

151151
> 注/Note: 部分云MySQL需指定`DB_AUTH_PLUGIN``mysql_native_password`
152152
153+
### MySQL 8.0 认证支持 / MySQL 8.0 Authentication Support
154+
155+
本系统完全支持 MySQL 8.0 的认证机制。MySQL 8.0 默认使用 `caching_sha2_password` 认证插件,提供更高的安全性。
156+
157+
This system fully supports MySQL 8.0 authentication mechanisms. MySQL 8.0 uses `caching_sha2_password` by default for enhanced security.
158+
159+
#### 认证插件对比 / Authentication Plugin Comparison
160+
161+
| 认证插件 / Plugin | 安全性 / Security | 兼容性 / Compatibility | 依赖要求 / Dependencies |
162+
|------------------|-------------------|------------------------|------------------------|
163+
| `mysql_native_password` | 中等 / Medium | 高 / High | 无 / None |
164+
| `caching_sha2_password` | 高 / High | 中等 / Medium | cryptography |
165+
166+
#### 配置建议 / Configuration Recommendations
167+
168+
**生产环境 / Production**(推荐 / Recommended):
169+
```ini
170+
DB_AUTH_PLUGIN=caching_sha2_password
171+
```
172+
173+
**开发环境 / Development**(简化配置 / Simplified):
174+
```ini
175+
DB_AUTH_PLUGIN=mysql_native_password
176+
```
177+
178+
#### 依赖安装 / Dependency Installation
179+
180+
使用 `caching_sha2_password` 时需要安装 `cryptography` 包(已包含在 requirements.txt 中):
181+
182+
When using `caching_sha2_password`, the `cryptography` package is required (already included in requirements.txt):
183+
184+
```bash
185+
pip install cryptography
186+
```
187+
188+
详细配置指南请参考:[MySQL 8.0 认证插件支持指南](docs/mysql8_authentication.md)
189+
190+
For detailed configuration guide, see: [MySQL 8.0 Authentication Plugin Support Guide](docs/mysql8_authentication.md)
191+
153192
---
154193

155194
## 6. 自动化与资源管理优化 / Automation & Resource Management Enhancements

example.env

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,11 @@ MYSQL_USER=root # MySQL用户名
99
MYSQL_PASSWORD= # MySQL密码(留空表示无密码)
1010
MYSQL_DATABASE=testdb # 要连接的数据库名
1111
DB_CONNECTION_TIMEOUT=5 # 连接超时时间(秒)
12+
13+
# MySQL 8.0 认证插件配置
14+
# - mysql_native_password: 兼容性好,不需要额外依赖,但安全性较低
15+
# - caching_sha2_password: MySQL 8.0 默认,安全性高,需要 cryptography 包
16+
# 如果使用 MySQL 8.0 且用户采用 caching_sha2_password,请确保已安装 cryptography 包
1217
DB_AUTH_PLUGIN=mysql_native_password # 认证插件类型
1318

1419
# 数据库连接池配置
@@ -26,7 +31,7 @@ ENV_TYPE=development
2631

2732
# 安全配置
2833
# 允许的风险等级: LOW(查询), MEDIUM(安全修改), HIGH(结构变更), CRITICAL(危险操作)
29-
ALLOWED_RISK_LEVELS=LOW,MEDIUM
34+
ALLOWED_RISK_LEVELS=LOW,MEDIUM,HIGH
3035

3136
# 是否允许查询敏感字段信息(密码,凭证等)
3237
ALLOW_SENSITIVE_INFO=false

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22
mcp>=1.4.1
33
aiomysql>=0.2.0
44
python-dotenv>=1.0.1
5-
sqlparse>=0.5.3
5+
sqlparse>=0.5.3
6+
cryptography>=3.4.8

src/db/mysql_operations.py

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,28 @@ def get_db_config():
6464
'db': config['database'], # 'database' -> 'db'
6565
'port': config['port'],
6666
'connect_timeout': config.get('connection_timeout', 5), # 'connection_timeout' -> 'connect_timeout'
67-
# auth_plugin在aiomysql中不直接支持,忽略此参数
67+
'charset': 'utf8mb4', # 确保字符集支持
6868
}
6969

70+
# MySQL 8.0 认证插件支持
71+
# 如果指定了认证插件且不是默认的mysql_native_password,则添加到配置中
72+
auth_plugin = config.get('auth_plugin', 'mysql_native_password')
73+
if auth_plugin != 'mysql_native_password':
74+
# 对于caching_sha2_password等现代认证插件,需要确保cryptography包可用
75+
try:
76+
import cryptography
77+
# 添加认证插件配置以支持caching_sha2_password
78+
aiomysql_config.update({
79+
'auth_plugin': auth_plugin
80+
})
81+
logger.debug(f"使用认证插件: {auth_plugin} (已检测到 cryptography 包)")
82+
except ImportError:
83+
logger.warning(f"检测到认证插件 {auth_plugin},但未安装 cryptography 包")
84+
logger.warning("将回退到 mysql_native_password 认证方式")
85+
logger.warning("要完全支持 MySQL 8.0 认证,请安装: pip install cryptography")
86+
else:
87+
logger.debug(f"使用认证插件: {auth_plugin}")
88+
7089
return aiomysql_config
7190

7291
# 自定义异常类,细化错误处理
@@ -176,7 +195,17 @@ def _finalizer(p=pool, lid=loop_id):
176195
elif "Can't connect" in error_msg or "Connection refused" in error_msg:
177196
raise MySQLServerError("无法连接到MySQL服务器,请检查服务是否启动")
178197
elif "Authentication plugin" in error_msg:
179-
raise MySQLAuthPluginError(f"认证插件问题: {error_msg},请尝试修改用户认证方式为mysql_native_password")
198+
current_auth = DatabaseConfig.AUTH_PLUGIN
199+
error_detail = f"认证插件问题: {error_msg}"
200+
if current_auth == 'caching_sha2_password':
201+
error_detail += "\n解决方案:"
202+
error_detail += "\n1. 确保已安装 cryptography 包: pip install cryptography"
203+
error_detail += "\n2. 或者修改用户认证方式为 mysql_native_password"
204+
error_detail += "\n3. 或者在 .env 中设置 DB_AUTH_PLUGIN=mysql_native_password"
205+
else:
206+
error_detail += f"\n当前认证插件配置: {current_auth}"
207+
error_detail += "\n请检查 MySQL 用户的认证插件设置是否匹配"
208+
raise MySQLAuthPluginError(error_detail)
180209
else:
181210
raise MySQLConnectionError(f"数据库连接失败: {error_msg}")
182211
except Exception as e:
@@ -239,7 +268,17 @@ async def get_db_connection(require_database: bool = True):
239268
elif "Can't connect" in error_msg or "Connection refused" in error_msg:
240269
raise MySQLServerError("无法连接到MySQL服务器,请检查服务是否启动")
241270
elif "Authentication plugin" in error_msg:
242-
raise MySQLAuthPluginError(f"认证插件问题: {error_msg},请尝试修改用户认证方式为mysql_native_password")
271+
current_auth = DatabaseConfig.AUTH_PLUGIN
272+
error_detail = f"认证插件问题: {error_msg}"
273+
if current_auth == 'caching_sha2_password':
274+
error_detail += "\n解决方案:"
275+
error_detail += "\n1. 确保已安装 cryptography 包: pip install cryptography"
276+
error_detail += "\n2. 或者修改用户认证方式为 mysql_native_password"
277+
error_detail += "\n3. 或者在 .env 中设置 DB_AUTH_PLUGIN=mysql_native_password"
278+
else:
279+
error_detail += f"\n当前认证插件配置: {current_auth}"
280+
error_detail += "\n请检查 MySQL 用户的认证插件设置是否匹配"
281+
raise MySQLAuthPluginError(error_detail)
243282
else:
244283
raise MySQLConnectionError(f"数据库连接失败: {error_msg}")
245284
except Exception as e:

0 commit comments

Comments
 (0)