Swagger 2.0本身并不提供访问权限的配置,但可以通过在应用程序中配置访问权限来限制对Swagger页面的访问。
1.在SpringSecurity中配置Swagger访问权限
如果您正在使用Spring Security,则可以通过在Security配置中添加以下内容来限制对Swagger UI的访问:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// ... other configuration ...
.authorizeRequests()
.antMatchers("/").authenticated() // 需要登录才能访问Swagger UI
.antMatchers("/swagger-resources/**").authenticated() // 需要登录才能访问Swagger资源
.antMatchers("/v2/api-docs").authenticated() // 需要登录才能访问API文档
// ... other configuration ...
}
}
2.在Spring Boot应用程序中禁用Swagger UI和Swagger资源
如果您想完全禁用Swagger UI和Swagger资源,则可以在或文件中添加以下配置:
=false
=/disabled
.=/disabled
这将禁用Swagger UI和Swagger资源,并在/disabled路径上提供404响应。
3.使用Swagger增加授权头部
您可以在 Swagger 的全局 Parameter 中增加授权头部,以便在访问接口时带上授权信息。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private ApiKey apiKey() {
return new ApiKey("Auth-Token", "Auth-Token", "header");
}
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.securitySchemes((apiKey())) // 增加ApiKey认证
.select()
.apis((""))
.paths(())
.build();
}
}
在Swagger UI上,将出现一个授权输入框,您可以在其中输入令牌或其他授权信息。