在Linux系统中配置Swagger权限管理,通常需结合Spring Security实现,以下是具体步骤:
添加依赖
在pom.xml
中引入Spring Security和Swagger相关依赖:
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
配置Spring Security
创建安全配置类,定义认证规则(如HTTP Basic、JWT等):
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v2/api-docs/**").authenticated() // 需认证的Swagger路径
.anyRequest().permitAll()
.and()
.httpBasic(); // 或使用其他认证方式(如JWT需替换为对应配置)
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(); // 密码加密(可选)
}
}
配置Swagger
确保Swagger配置类正确扫描API路径:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 替换为实际包路径
.paths(PathSelectors.any())
.build();
}
}
高级权限控制(可选)
hasRole("ADMIN")
。Bearer
安全方案,并在API端点中应用@PreAuthorize
等注解。ApiKey
安全方案,通过请求头传递密钥。测试验证
启动应用后,访问Swagger UI(如http://localhost:8080/swagger-ui.html
),需输入认证信息(用户名/密码或Token)方可访问受保护的API文档和接口。
说明:具体实现需根据项目技术栈选择认证方式(如Spring Security默认支持HTTP Basic、OAuth2等),Linux系统仅需确保依赖正确安装、服务正常运行即可。