通过向代码中添加以下类,我向现有的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应该是公开的,但是招摇的文档不应该公开。我想要一种向招摇的文档请求身份验证的方法,有人知道实现此目的的任何简单方法吗?
我试图用谷歌搜索它,但是我只能找到OAth的东西,但这是对端点的身份验证,而不是the脚的文档...
最佳答案
当swagger与spring boot应用程序集成时,将在/ v2 / api-docs端点提供Swagger文档。
为了保护资源,利用spring安全性并限制端点访问文档
<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。