Swagger(OpenAPI)是流行的API文档和测试工具,但在Linux生产环境中需要特别注意安全性。以下是保障Swagger安全的关键措施:
启用基本认证:在Swagger UI配置中添加HTTP基本认证
location /swagger-ui/ {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
}
集成现有认证系统:如OAuth2、JWT或LDAP
nginx
allow 192.168.1.0/24;
deny all;
java
@Profile("!prod")
@Configuration
public class SwaggerConfig { ... }
/v2/api-docs
和/swagger-ui.html
nginx
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
nginx
add_header X-Frame-Options "DENY";
add_header X-Content-Type-Options "nosniff";
add_header Content-Security-Policy "default-src 'self'";
容器安全:如果使用Docker,配置适当的用户权限和只读文件系统
USER nobody
VOLUME /tmp
资源限制:防止DoS攻击
limit_req_zone $binary_remote_addr zone=swagger:10m rate=5r/s;
通过实施这些措施,可以显著提高Linux环境中Swagger的安全性,同时保持其作为API文档和测试工具的价值。