Swagger (OpenAPI) 是一个强大的API文档工具,但它本身不直接提供权限控制功能。不过,你可以通过以下方法结合Swagger实现API权限控制:
# 在Swagger/OpenAPI规范中添加安全定义
securityDefinitions:
apiKey:
type: apiKey
name: X-API-KEY
in: header
paths:
/protected:
get:
security:
- apiKey: []
responses:
200:
description: OK
securityDefinitions:
oauth2:
type: oauth2
flow: implicit
authorizationUrl: https://example.com/oauth/authorize
scopes:
read: Grants read access
write: Grants write access
使用Kong或Traefik等API网关:
Kong示例配置:
# 添加JWT插件
curl -X POST http://localhost:8001/plugins \
--data "name=jwt" \
--data "config.claims_to_verify=exp"
Node.js示例(使用express-swagger-generator):
const express = require('express');
const swagger = require('express-swagger-generator')(app);
app.use((req, res, next) => {
if (req.path.startsWith('/api-docs') && !req.user.isAdmin) {
return res.status(403).send('Forbidden');
}
next();
});
Spring Boot示例:
@Configuration
public class SwaggerSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/swagger-ui/**").hasRole("ADMIN")
.antMatchers("/v3/api-docs").hasRole("ADMIN");
}
}
paths:
/admin:
get:
tags: [admin]
security:
- oauth2: [admin]
/user:
get:
tags: [user]
security:
- oauth2: [user]
可以通过扩展Swagger规范添加自定义属性:
x-permissions:
requiredRoles: [admin]
allowedDepartments: [finance, hr]
使用Docker部署Swagger UI:
docker pull swaggerapi/swagger-ui
docker run -p 8080:8080 -e API_URL=https://your-api.com/swagger.json swaggerapi/swagger-ui
Nginx反向代理配置:
location /swagger/ {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://swagger-ui:8080/;
}
使用Let's Encrypt保护Swagger端点:
sudo certbot --nginx -d swagger.yourdomain.com
生产环境注意事项:
审计日志:
# 使用journalctl跟踪访问日志
journalctl -u your-api-service -f | grep "/swagger"
通过以上方法,你可以在Linux环境中安全地使用Swagger进行API权限控制,确保只有授权用户能够访问特定的API端点。