Spring Boot Swagger UI-保护UI访问 [英] Spring Boot Swagger UI - Protect UI Access
问题描述
通过向代码中添加以下类,我向现有的springboot REST API添加了一个简单的swagger UI:
I added a simple swagger UI to my existing springboot REST API by adding the following class to my code:
@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应该是公开的,但是昂首阔步的文档不应该公开.我想要一种向庞大的文档请求身份验证的方法,有人知道实现此目的的任何简单方法吗?
My problem is that the API should be public, but the swagger docs should not. I would like a way of requesting authentication to the swagger documentation, anyone knows any simple way of achieving this?
我试图用谷歌搜索它,但是我只能找到OAth的东西,但这是对端点的身份验证,而不是详尽的文档...
I tried to google it but I could only find OAth stuff, but this is authentication for the endpoints not the swagger documentation...
推荐答案
Swagger文档将在/v2/api-docs 端点上可用.
Swagger docs will be available at /v2/api-docs endpoint when swagger integrated with spring boot application.
为了保护资源,利用spring安全性并限制端点访问文档
Inorder to protect the resource , make use of spring security and restrict the endpoint for accessing the docs
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
安全配置:仅对用户限制对端点的访问
Security configuration : restricting access to the endpoint only to the users
@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.
Additionally, swagger-ui.html can also be secured based on the requirement.
这篇关于Spring Boot Swagger UI-保护UI访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!