在Spring Boot项目中使用Swagger时,可以通过配置文件来限制对Swagger UI的访问。以下是一个使用Spring Security来限制对Swagger UI的访问的示例:
- 首先,在
pom.xml中添加Spring Security依赖: 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>- 接下来,在
application.properties或application.yml中配置Swagger的基本路径访问权限: 
# application.properties
springfox.documentation.swagger-ui.enabled=true- 然后,配置Spring Security来保护Swagger UI路径。在
WebSecurityConfigurerAdapter的实现中添加对Swagger UI的保护: 
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
 
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 允许对Swagger UI的访问
            .authorizeRequests()
            .antMatchers("/swagger-ui.html").permitAll()
            .antMatchers("/v2/api-docs").permitAll()
            .antMatchers("/swagger-resources/**").permitAll()
            .antMatchers("/webjars/**").permitAll()
            // 其他所有请求都需要验证
            .anyRequest().authenticated()
            .and()
            // 禁用CSRF保护,因为Swagger不支持CSRF
            .csrf().disable();
    }
}在上述配置中,我们通过.antMatchers()方法指定了对Swagger UI资源的访问权限,使用.permitAll()来允许它们被匿名访问。同时,关闭了CSRF保护,因为Swagger UI不支持CSRF令牌。
确保你的应用已经配置了用户源和用户详情服务,这样才能保护其他路径不受未授权访问。
以上代码仅供参考,具体实现可能需要根据实际项目需求进行调整。