Swagger (现称OpenAPI)是一个流行的API文档工具,但在生产环境中需要适当的权限控制来保护敏感API信息。以下是在Linux系统中实现Swagger权限控制的几种方法:
最简单的方法是在Swagger UI前添加基础认证:
location /swagger/ {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
# 代理到你的Swagger服务
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
创建密码文件:
sudo htpasswd -c /etc/nginx/.htpasswd username
限制只有特定IP可以访问Swagger:
location /swagger/ {
allow 192.168.1.100; # 允许的IP
allow 10.0.0.0/8; # 允许的IP段
deny all; # 拒绝其他所有
proxy_pass http://localhost:8080;
}
在应用代码中实现权限控制:
@Configuration
public class SwaggerSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/swagger-ui/**")
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
如果你使用API网关(如Kong, Apigee等),可以在网关层设置访问策略:
# 为Swagger路由添加基本认证插件
curl -X POST http://localhost:8001/routes/{route_id}/plugins \
--data "name=basic-auth" \
--data "config.hide_credentials=true"
在开发/生产环境区分显示Swagger:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.enable(!"prod".equals(System.getenv("APP_ENV")));
}
}
在OpenAPI规范中定义安全方案:
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
security:
- bearerAuth: []
通过以上方法,你可以在Linux系统中有效地控制对Swagger的访问,保护API文档不被未授权访问。