在 Debian 上部署的 Swagger(如 Swagger UI / Swagger Editor / Springdoc-openapi 等) 做权限控制,常见做法分 运行时访问控制 和 代码层控制 两类。下面按使用场景说明。
如果 Swagger 通过 Nginx 暴露:
sudo apt install nginx apache2-utils
生成密码:
htpasswd -c /etc/nginx/swagger.htpasswd admin
Nginx 配置:
location /swagger-ui/ {
auth_basic "Swagger Restricted";
auth_basic_user_file /etc/nginx/swagger.htpasswd;
proxy_pass http://127.0.0.1:8080;
}
✅ 优点:不改动代码
❌ 缺点:只有账号密码,无细粒度权限
location /swagger-ui/ {
allow 192.168.1.0/24;
deny all;
}
spring:
profiles:
active: prod
@Profile("!prod")
@Configuration
public class SwaggerConfig {}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v3/api-docs/**")
.hasRole("ADMIN")
.anyRequest().authenticated();
}
.antMatchers("/swagger-ui.html").authenticated()
@Operation(security = @SecurityRequirement(name = "bearerAuth"))
@GetMapping("/admin")
public String admin() {
return "admin";
}
docker run -e SWAGGER_JSON=/foo/api.yaml \
-p 8080:8080 swaggerapi/swagger-ui
配合 Nginx 做认证即可。
| 场景 | 推荐方案 |
|---|---|
| 内部调试 | Nginx + IP 白名单 |
| 对外展示 | Nginx Basic Auth |
| 企业系统 | Spring Security |
| 生产环境 | 直接禁用 |
如果你能告诉我:
我可以给你一份可直接用的配置。