1. 首页
  2. 软件开发
  3. JAVA
  4. SpringBoot配置Swagger开启页面访问限制

SpringBoot配置Swagger开启页面访问限制

  • 发布于 2024-08-16
  • 0 次阅读

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

        在 Spring Boot 项目中配置 Swagger 时,开启页面访问限制通常意味着你希望控制哪些用户或角色可以访问 Swagger UI 文档页面。由于 Swagger UI 是一个静态资源,它本身并不直接支持基于角色的访问控制(RBAC)。但是,你可以通过 Spring Security 来间接实现这一点。

        下面是一个基本的步骤,说明如何在使用 Spring Boot 和 Swagger 时,结合 Spring Security 来限制对 Swagger UI 的访问:

1. 添加依赖

        首先,确保你的项目中包含了 Spring Boot 的 starter-web、starter-security 以及 swagger 的依赖。例如,在 Maven 的pom.xml中:

<!-- Spring Boot Starter Web -->  
<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-web</artifactId>  
</dependency>  
  
<!-- Spring Boot Starter Security -->  
<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-security</artifactId>  
</dependency>  
  
<!-- Swagger -->  
<dependency>  
    <groupId>io.springfox</groupId>  
    <artifactId>springfox-swagger2</artifactId>  
    <version>你的版本号</version>  
</dependency>  
<dependency>  
    <groupId>io.springfox</groupId>  
    <artifactId>springfox-swagger-ui</artifactId>  
    <version>你的版本号</version>  
</dependency>

2. 配置 Spring Security

        在你的 Spring Security 配置中,你可以定义哪些路径需要被保护,以及如何保护它们。对于 Swagger UI,通常其路径是/swagger-ui.html(这取决于你的配置,可能有所不同)。

@Configuration  
@EnableWebSecurity  
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {  
  
    @Override  
    protected void configure(HttpSecurity http) throws Exception {  
        http  
            // ... 其他配置  
            .authorizeRequests()  
                .antMatchers("/swagger-ui.html").hasRole("ADMIN") // 限制只有ADMIN角色可以访问Swagger UI  
                .antMatchers("/webjars/**").hasRole("ADMIN") // Swagger UI所需资源也需要限制  
                .antMatchers("/v2/api-docs").permitAll() // 允许所有人访问Swagger API文档  
                .anyRequest().authenticated()  
                .and()  
            .formLogin()  
                .and()  
            .httpBasic();  
    }  
  
    // 其他配置...  
}

3. 配置 Swagger

        确保你的 Swagger 配置正确设置了 Swagger 的 API 文档路径,以便 Spring Security 的配置可以正确地应用。

@Configuration  
@EnableSwagger2  
public class SwaggerConfig {  
  
    @Bean  
    public Docket api() {  
        return new Docket(DocumentationType.SWAGGER_2)  
            .select()  
            .apis(RequestHandlerSelectors.any())  
            .paths(PathSelectors.any())  
            .build()  
            .apiInfo(metaData());  
    }  
  
    private ApiInfo metaData() {  
        // 配置Swagger的元数据信息  
        return new ApiInfoBuilder()  
            .title("你的API文档")  
            .description("API描述")  
            .version("1.0")  
            .build();  
    }  
}

4. 测试

现在,当你尝试访问/swagger-ui.html时,你应该会被重定向到 Spring Security 的登录页面(如果你还没有登录)。只有具有ADMIN角色的用户才能访问 Swagger UI。

请注意,以上代码示例和步骤可能需要根据你的具体项目配置进行适当调整。