1. 安装Swagger及相关依赖
在Linux系统上,首先需要安装Swagger的核心工具(如swagger-jsdoc
、swagger-ui-express
)及安全相关的依赖(如passport
、jsonwebtoken
)。以Node.js项目为例,可通过npm全局安装Swagger工具:
sudo apt update && sudo apt install nodejs npm # 安装Node.js和npm
npm install -g swagger-jsdoc swagger-ui-express # 安装Swagger核心工具
npm install passport passport-jwt jsonwebtoken # 安装安全认证依赖
确保系统已安装Node.js(建议版本≥14)和npm,避免依赖冲突。
2. 定义OpenAPI安全方案
在Swagger规范文件(如swagger.yaml
或swagger.json
)中,明确安全协议和认证方式。推荐使用OAuth2(适用于授权码流程)或JWT(适用于无状态认证),并定义scopes(权限范围):
openapi: 3.0.0
info:
title: Secure API
version: 1.0.0
components:
securitySchemes:
BearerAuth: # JWT认证方案
type: http
scheme: bearer
bearerFormat: JWT
OAuth2: # OAuth2授权码流程
type: oauth2
flows:
authorizationCode:
authorizationUrl: https://auth.example.com/oauth/authorize
tokenUrl: https://auth.example.com/oauth/token
scopes:
read: Grants read access to resources
write: Grants write access to resources
paths:
/data:
get:
summary: Get secure data
security:
- BearerAuth: [] # 应用JWT认证
- OAuth2: ["read"] # 应用OAuth2认证(需read scope)
此配置要求客户端在调用/data
端点时,必须提供有效的JWT令牌或OAuth2访问令牌(包含read
scope)。
3. 集成安全认证逻辑
在后端服务中实现认证中间件,验证客户端提供的凭证。以JWT为例,可使用jsonwebtoken
库创建验证过滤器:
const jwt = require('jsonwebtoken');
const express = require('express');
const app = express();
// JWT验证中间件
function authenticateJWT(req, res, next) {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(' ')[1]; // 提取Bearer令牌
jwt.verify(token, 'your-secret-key', (err, user) => { // 验证令牌签名
if (err) {
return res.sendStatus(403); // 无效/过期令牌
}
req.user = user; // 将用户信息附加到请求对象
next();
});
} else {
res.sendStatus(401); // 未提供令牌
}
}
// 保护API端点
app.get('/data', authenticateJWT, (req, res) => {
res.json({ message: 'Secure data accessed successfully' });
});
app.listen(3000, () => console.log('Server running on port 3000'));
对于OAuth2,可使用passport-oauth2
库实现授权码流程,验证access_token
的有效性(如通过tokenUrl
向认证服务器确认)。
4. 配置Swagger UI安全访问
为了让Swagger UI(如swagger-ui-express
)支持安全认证,需在UI配置中添加安全方案,提示用户输入凭证:
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, {
oauth: {
clientId: 'your-client-id', // OAuth2客户端ID
appName: 'Swagger UI',
scopes: {
read: 'Read access',
write: 'Write access'
}
},
requestInterceptor: (request) => {
// 在请求头中自动添加JWT令牌(若已登录)
const token = localStorage.getItem('jwtToken');
if (token) {
request.headers.Authorization = `Bearer ${token}`;
}
return request;
}
}));
访问http://your-server-ip:3000/api-docs
时,Swagger UI会提示用户登录(OAuth2)或输入JWT令牌(Bearer Auth),确保只有授权用户能查看和测试API。
5. 强化Linux环境安全
sudo apt install certbot python3-certbot-nginx # 安装Certbot
sudo certbot --nginx -d your-domain.com # 获取并配置证书
iptables
限制API端口(如443)的访问,仅允许可信IP段:sudo iptables -A INPUT -p tcp --dport 443 -s 192.168.1.0/24 -j ACCEPT # 允许内网访问
sudo iptables -A INPUT -p tcp --dport 443 -j DROP # 拒绝其他IP
systemd
限制API服务的运行权限(如禁止root用户运行):# /etc/systemd/system/api.service
[Service]
User=api-user # 非root用户
Group=api-group
CapabilityBoundingSet=CAP_NET_BIND_SERVICE # 仅允许绑定端口
PrivateTmp=true # 隔离临时文件
NoNewPrivileges=true # 禁止提权
Falco
检测异常API访问(如403响应),使用Prometheus+Grafana
监控API流量:# Falco规则示例(检测未授权访问)
- rule: Unauthorized API Access
desc: Detect 403 responses from API endpoints
condition: >
evt.type=open and
fd.name contains "/api/" and
evt.res=403
output: "Unauthorized API access attempt (user=%user.name proc=%proc.name)"
apt
自动更新系统和依赖项,修复已知漏洞:sudo apt upgrade -y && sudo apt autoremove -y # 更新系统
npm audit fix # 修复Node.js依赖漏洞
6. 测试与验证
curl
测试API认证:curl -H "Authorization: Bearer your-jwt-token" https://your-server-ip:3000/data # 测试JWT
curl -u admin:secret https://your-server-ip:3000/protected # 测试Basic Auth
/api-docs
,验证是否需要登录,测试受保护端点的访问权限。