在Linux系统中,Swagger权限管理需结合Spring Security实现,核心策略如下:
spring-boot-starter-security
,创建配置类继承WebSecurityConfigurerAdapter
,定义访问控制规则。hasRole()
或hasAuthority()
限制特定角色访问Swagger UI或API端点,例如仅ADMIN
角色可访问文档。antMatchers()
指定Swagger相关路径(如/swagger-ui/**
、/v2/api-docs/**
)的访问权限。示例代码(基础认证配置):
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v2/api-docs/**").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic(); // 基础认证
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(); // 密码加密
}
}
以上策略需结合具体业务场景调整,生产环境建议使用数据库存储用户信息、配置HTTPS及更复杂的权限规则。