Linux上Swagger认证实践
总体思路
| 方案 | 适用场景 | 关键配置要点 |
|---|---|---|
| API Key | 服务到服务调用、简单管控 | 在 securityDefinitions 定义 type: apiKey,指定 in: header 或 in: query |
| HTTP Basic | 内部管理接口、快速接入 | 在 securityDefinitions 定义 type: basic,服务端校验用户名/密码 |
| OAuth2 / OpenID Connect | 第三方授权、细粒度权限 | 定义 flow、authorizationUrl、tokenUrl 与 scopes,UI 提供授权弹窗 |
| 以上方案均可在 Swagger/OpenAPI 规范中声明,并通过 Swagger UI 使用。 |
方案一 API Key 认证
swagger: '2.0'
info:
title: Sample API
version: '1.0.0'
securityDefinitions:
ApiKeyAuth:
type: apiKey
name: Authorization
in: header
paths:
/users:
get:
security:
- ApiKeyAuth: []
app.use((req, res, next) => {
const key = req.headers['authorization'];
if (key === 'your-secret-api-key') return next();
res.status(401).send('Unauthorized');
});
name 与后端读取的头部保持一致(如 Authorization),生产环境务必使用 HTTPS 传输密钥。方案二 HTTP Basic 认证
swagger: '2.0'
info:
title: Sample API
version: '1.0.0'
securityDefinitions:
BasicAuth:
type: basic
paths:
/users:
get:
security:
- BasicAuth: []
const basicAuth = require('express-basic-auth');
app.use('/api-docs', basicAuth({
users: { 'admin': 'secret' },
challenge: true,
unauthorizedResponse: { message: 'Unauthorized', status: 401 }
}));
方案三 OAuth2 与 OpenID Connect
swagger: '2.0'
info:
title: Sample API
version: '1.0.0'
securityDefinitions:
OAuth2:
type: oauth2
flow: accessCode
authorizationUrl: https://example.com/oauth/authorize
tokenUrl: https://example.com/oauth/token
scopes:
read: Grants read access
write: Grants write access
paths:
/users:
get:
security:
- OAuth2: [read]
部署与运维建议
server {
listen 80;
server_name yourdomain.com;
location /api/ {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
# 创建账号:sudo htpasswd -c /etc/nginx/.htpasswd username