feat: 添加请求认证中间件保护 API 端点
- 新增 auth-middleware.js 验证客户端 API Key - 支持 Authorization: Bearer <key> 和 x-api-key 两种方式 - API Keys 只通过环境变量配置(安全最佳实践) - 公开路径: /, /health, /status - 可配置 /v1/models 是否需要认证 - 启动时输出认证状态日志 配置方式: AUTH_ENABLED=true API_KEYS=sk-key1,sk-key2 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
12
server.js
12
server.js
@@ -6,6 +6,7 @@ import { initializeAuth } from './auth.js';
|
||||
import { initializeUserAgentUpdater } from './user-agent-updater.js';
|
||||
import './sls-logger.js'; // 初始化阿里云日志服务
|
||||
import { sanitizeForLog } from './log-sanitizer.js';
|
||||
import { authMiddleware, getAuthConfig } from './auth-middleware.js';
|
||||
|
||||
// ============================================================================
|
||||
// 全局错误处理 - 必须在应用启动前注册
|
||||
@@ -147,6 +148,9 @@ app.use((req, res, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
// 请求认证中间件
|
||||
app.use(authMiddleware);
|
||||
|
||||
app.use(router);
|
||||
|
||||
app.get('/', (req, res) => {
|
||||
@@ -243,6 +247,14 @@ app.use((err, req, res, next) => {
|
||||
loadConfig();
|
||||
logInfo('Configuration loaded successfully');
|
||||
logInfo(`Dev mode: ${isDevMode()}`);
|
||||
|
||||
// Log auth status
|
||||
const authConfig = getAuthConfig();
|
||||
if (authConfig.enabled) {
|
||||
logInfo(`Auth enabled with ${authConfig.apiKeys.size} API key(s)`);
|
||||
} else {
|
||||
logInfo('Auth disabled - API endpoints are publicly accessible');
|
||||
}
|
||||
|
||||
// Initialize User-Agent version updater
|
||||
initializeUserAgentUpdater();
|
||||
|
||||
Reference in New Issue
Block a user