安全: 优化CORS配置,支持环境变量控制允许的来源
问题描述: - CORS配置使用origin: true允许所有来源 - 无法限制跨域访问,存在CSRF风险 - 生产环境应该只允许特定域名访问 修复内容: 1. 从环境变量ALLOWED_ORIGINS读取允许的来源列表 2. 支持多个域名配置(逗号分隔) 3. 实现origin验证回调函数 4. 默认允许所有(*),但在生产环境会发出警告 5. 记录并拒绝未授权来源的请求 配置示例: - 开发环境: ALLOWED_ORIGINS=* - 生产环境: ALLOWED_ORIGINS=https://yourdomain.com,https://www.yourdomain.com 影响范围: 跨域请求控制 测试建议: - 配置ALLOWED_ORIGINS后验证只有指定域名可以访问 - 生产环境使用*时应该看到警告日志 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -18,8 +18,36 @@ const { generateToken, authMiddleware, adminMiddleware } = require('./auth');
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 40001;
|
||||
|
||||
|
||||
// 配置CORS
|
||||
const allowedOrigins = process.env.ALLOWED_ORIGINS
|
||||
? process.env.ALLOWED_ORIGINS.split(',').map(origin => origin.trim())
|
||||
: ['*'];
|
||||
|
||||
const corsOptions = {
|
||||
credentials: true,
|
||||
origin: (origin, callback) => {
|
||||
// 允许所有来源(仅限开发环境)
|
||||
if (allowedOrigins.includes('*')) {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
console.warn('⚠️ 警告: 生产环境建议配置具体的ALLOWED_ORIGINS,而不是使用 *');
|
||||
}
|
||||
callback(null, true);
|
||||
return;
|
||||
}
|
||||
|
||||
// 允许来自配置列表中的域名
|
||||
if (!origin || allowedOrigins.includes(origin)) {
|
||||
callback(null, true);
|
||||
} else {
|
||||
console.warn(`[CORS] 拒绝来自未授权来源的请求: ${origin}`);
|
||||
callback(new Error('CORS策略不允许来自该来源的访问'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 中间件
|
||||
app.use(cors({ credentials: true, origin: true }));
|
||||
app.use(cors(corsOptions));
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
|
||||
|
||||
Reference in New Issue
Block a user