Swagger是一个流行的API文档工具,但在生产环境中暴露Swagger UI可能会带来安全风险。以下是在Linux环境中配置Swagger权限控制的几种方法:
@Configuration
public class SwaggerSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatcher(EndpointRequest.toAnyEndpoint())
.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v3/api-docs/**")
.hasRole("ADMIN") // 只允许ADMIN角色访问
.and()
.httpBasic();
}
}
在Nginx配置中添加访问限制:
location /swagger-ui/ {
# 只允许特定IP访问
allow 192.168.1.100;
allow 10.0.0.1;
deny all;
# 或者要求基本认证
auth_basic "Swagger Access";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://localhost:8080;
}
创建密码文件:
sudo htpasswd -c /etc/nginx/.htpasswd username
// 只在开发环境启用Swagger
if (process.env.NODE_ENV === 'development') {
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
}
@Profile("!prod") // 不在生产环境启用
@Configuration
@EnableSwagger2
public class SwaggerConfig {
// Swagger配置
}
如果不需要Swagger UI,可以在生产环境中完全禁用:
对于Spring Boot应用:
# application-prod.properties
springfox.documentation.enabled=false
在API网关层面添加访问控制策略,只允许特定用户或IP访问Swagger端点。
根据您的具体技术栈和安全需求,可以选择上述一种或多种方法组合来实现Swagger的权限控制。