Spring Boot Swagger UI - 保护 UI 访问

标签 spring authentication spring-boot swagger-ui

我通过将以下类添加到我的代码中,向我现有的 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/

相关文章:

Spring + Vaadin 整合设计模式

java - 如何在 Spring-Integration 中将 SOAPAction header 添加到 HTTP 消息中?

python - 如何使用 Python 社交身份验证获得唯一的电子邮件

ruby-on-rails - Ruby on Rails Devise,身份验证失败时如何更改登录路径?

java - 如何在java中将文本字段中的值插入数据库

javascript - 在 Spring Boot 中,在单击事件期间 Html 页面重定向并使用 Jquery/Thymeleaf 加载下拉组件中的值

java - 在spring框架中读取带注解的属性文件

java - RabbitMQ Spring 死信配置不起作用

java - 如何在自定义过滤器中验证 spring security antmatcher

java - 在 @RequestParam 中绑定(bind)列表包含方括号