Swagger作为一个API文档工具,在生产环境中需要适当的权限管理来保护敏感API信息。以下是几种在Linux环境下实现Swagger权限管理的方案:
最简单的方式是通过HTTP基础认证:
# Nginx配置示例
location /swagger/ {
auth_basic "Swagger Access";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://localhost:8080;
}
创建密码文件:
sudo htpasswd -c /etc/nginx/.htpasswd username
对于Spring Boot应用:
@Configuration
@EnableWebSecurity
public class SwaggerSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/swagger-ui/**")
.authorizeRequests()
.anyRequest().hasRole("API_DOCS")
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("swaggeruser")
.password("{noop}password")
.roles("API_DOCS");
}
}
location /swagger/ {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
proxy_pass http://localhost:8080;
}
在Kong、Apigee等API网关中配置权限:
# Kong示例
curl -X POST http://kong:8001/services/{service}/plugins \
--data "name=basic-auth" \
--data "config.hide_credentials=true"
对于Swagger UI,可以通过配置实现简单权限控制:
const ui = SwaggerUIBundle({
url: "/api-docs",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
layout: "StandaloneLayout",
requestInterceptor: (req) => {
if (req.url.includes('/api-docs')) {
req.headers.Authorization = 'Basic ' + btoa('username:password');
}
return req;
}
});
location /swagger/ {
auth_jwt "Restricted";
auth_jwt_key_file /path/to/jwt/key;
proxy_pass http://localhost:8080;
}
选择哪种方案取决于您的具体需求、技术栈和安全要求。对于大多数生产环境,建议至少使用基础认证结合IP限制的方式。