Swagger本身不直接提供权限管理功能,但在Linux环境下,可通过 集成后端安全框架(如Spring Security) 结合 身份验证 与 授权机制 实现API及文档的权限控制。以下是具体实现步骤:
Spring Security是Java生态中常用的安全框架,需先将其集成到Spring Boot项目中(Swagger通常与Spring Boot配合使用)。
在pom.xml中添加以下依赖:
<!-- Spring Security核心依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Swagger 2依赖(若使用Swagger 3,替换为springdoc-openapi-starter-webmvc-ui) -->
<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>
创建SecurityConfig类(继承WebSecurityConfigurerAdapter),定义认证方式(如内存认证、数据库认证)和授权规则(哪些路径需要认证)。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// Swagger UI及API文档路径需认证
.antMatchers("/swagger-ui/**", "/v2/api-docs/**", "/swagger-resources/**").authenticated()
// 其他路径允许所有用户访问(生产环境建议细化)
.anyRequest().permitAll()
.and()
.httpBasic(); // 使用HTTP Basic认证(弹出登录框)
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 内存用户配置(生产环境建议用数据库)
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER") // {noop}表示不加密密码
.and()
.withUser("admin").password("{noop}admin").roles("ADMIN");
}
}
若需更安全的无状态认证,可使用JWT(JSON Web Token):
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/swagger-ui/**", "/v2/api-docs/**").hasRole("USER") // 需USER角色
.antMatchers("/admin/**").hasRole("ADMIN") // 管理员路径
.anyRequest().permitAll()
.and()
.oauth2ResourceServer().jwt(); // 启用JWT认证
}
@Bean
public JwtDecoder jwtDecoder() {
// 从授权服务器获取JWK Set(JSON Web Key Set)
return NimbusJwtDecoder.withJwkSetUri("https://your-auth-server/.well-known/jwks.json").build();
}
}
创建SwaggerConfig类,定义API文档的扫描范围,并添加安全方案(如OAuth2、API Key),使Swagger UI支持权限认证。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) // 扫描controller包
.paths(PathSelectors.any())
.build();
}
}
若后端使用OAuth2,需在Swagger中定义安全方案,使用户访问文档时需授权:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build()
.securitySchemes(Arrays.asList(bearerAuth())) // 添加Bearer Token认证
.securityContexts(Arrays.asList(securityContext())); // 定义安全上下文
}
private SecurityScheme bearerAuth() {
return new OAuth2SchemeBuilder()
.type(SecurityScheme.Type.OAUTH2)
.flow(OAuth2Scheme.Flow.PASSWORD)
.tokenUrl("https://your-auth-server/oauth/token")
.scopes(new AuthorizationScope("read", "Read access"), new AuthorizationScope("write", "Write access"))
.build();
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(Arrays.asList(new SecurityReference("bearerAuth", new AuthorizationScope[]{})))
.forPaths(PathSelectors.any())
.build();
}
}
java -jar your-application.jar)。http://your-server-address:port/swagger-ui.html。user)和密码(如password)。/admin/**),则无法查看或调用该接口。@PreAuthorize("hasRole('ADMIN')")),并在Swagger中通过注释反映角色关联(如@ApiOperation(value = "Admin API", authorizations = {@Authorization(value = "bearerAuth")}))。swagger-security-example等开源项目,快速集成OAuth2、RBAC等功能;或用OpenAPI-to-Swagger工具生成包含权限信息的Swagger文档。通过以上步骤,可在Linux环境下实现Swagger的权限控制,确保API文档及接口的安全性。