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
,驗證是否需要登錄,測試受保護端點的訪問權限。