我通过将以下类添加到我的代码中,向我现有的 springboot REST API 添加了一个简单的 swagger UI:
@EnableSwagger2
@Configuration
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.paths(PathSelectors.regex("/v1.*"))
.build()
.pathMapping("/")
.apiInfo(metadata());
}
private ApiInfo metadata() {
return new ApiInfoBuilder()
.title("My awesome API")
.description("Some description")
.version("1.0")
.build();
}
}
我的问题是 API 应该是公开的,但 swagger 文档不应该是公开的。我想要一种请求对 swagger 文档进行身份验证的方法,有人知道实现此目的的任何简单方法吗?
我试图用谷歌搜索它,但我只能找到 OAth 的东西,但这是端点的身份验证,而不是 swagger 文档......
最佳答案
Swagger 文档将在 提供/v2/api-docs swagger 与 Spring Boot 应用程序集成时的端点。
为了保护资源,利用spring security,限制访问文档的端点。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
安全配置 : 仅限用户访问端点
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/v2/api-docs").authenticated()
.and()
.httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
此外,还可以根据需要保护 swagger-ui.html。
关于Spring Boot Swagger UI - 保护 UI 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45766296/