mcpField
A
api-security-hardening

api-security-hardening

github.com/secondsky安全240496 次安装5 周前更新
代码仓库

关于 api-security-hardening

面向开发者的 REST API 安全加固技能,介绍中间件、输入验证、安全响应头和实用检查清单,以应对常见漏洞。

主要功能

  1. 01Express 安全中间件
  2. 02输入验证与净化
  3. 03安全响应头配置
  4. 04API 安全检查清单
  5. 05Python 与 Nginx 指引

适用场景

  1. 01加固 Express REST API
  2. 02验证用户提交的数据
  3. 03限制跨域访问
  4. 04审查 API 安全措施

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/secondsky/claude-skills --skill api-security-hardening

安装后在 Claude Code 中输入/api-security-hardening确认已加载。

附带文件references/python-nginx.md

详细介绍

API 安全加固

通过多层安全防护,保护 REST API 免受常见漏洞侵害。

安全中间件栈(Express)

const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const mongoSanitize = require('express-mongo-sanitize');

app.use(helmet());
app.use(mongoSanitize());
// For input sanitization, see the `xss-prevention` skill — do NOT use the
// deprecated `xss-clean` package (unmaintained since 2018; its own README
// recommends migrating off it).

app.use('/api/', rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100
}));

app.use('/api/auth/', rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 5
}));

输入验证

const { body, validationResult } = require('express-validator');
const escapeHtml = require('escape-html');

app.post('/users',
  body('email').isEmail().normalizeEmail(),
  body('password').isLength({ min: 8 }).matches(/[A-Z]/).matches(/[0-9]/),
  // express-validator v7+ removed the built-in .escape() sanitizer; use a
  // customSanitizer backed by `escape-html` to HTML-escape the value.
  body('name').trim().isLength({ max: 100 }).customSanitizer(v => escapeHtml(v)),
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    // Process request
  }
);

安全标头

app.use((req, res, next) => {
  res.setHeader('Content-Security-Policy', "default-src 'self'");
  res.setHeader('X-Frame-Options', 'DENY');
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
  res.setHeader('X-XSS-Protection', '1; mode=block');
  next();
});

安全检查清单

  • 所有地方均使用 HTTPS
  • 所有受保护的路由均启用身份验证
  • 输入验证和清理
  • 已启用速率限制
  • 已配置安全标头
  • CORS 仅允许指定来源
  • 生产环境错误中不包含堆栈跟踪
  • 已启用审计日志记录
  • 定期更新依赖项

其他实现

请参阅 references/python-nginx.md,了解:

  • Python FastAPI 安全中间件
  • 带密码规则的 Pydantic 输入验证
  • Nginx SSL/TLS 和安全标头配置
  • HTTP 参数污染防护

切勿执行

  • 不经验证就信任用户输入
  • 在生产环境中返回详细错误信息
  • 将机密信息存储在代码中
  • 使用 GET 执行会更改状态的操作
  • 为图方便而禁用安全防护

评论

支持 Markdown