关闭swagger-ui
时间: 2025-06-14 11:49:32 浏览: 18
Swagger UI 是一个非常方便的工具,它可以帮助开发者测试和文档化 RESTful API 接口。有时出于安全考虑或者其他需求,我们可能会需要关闭 Swagger UI 的访问。
### Spring Boot 中关闭 Swagger UI 访问
如果你是在基于Spring Boot的应用程序中配置并想要关闭对`swagger-ui.html`页面的访问权限的话,可以采取以下几种方案:
#### 1. 移除依赖项
最直接的方式是从项目的 `pom.xml` 或者 `build.gradle` 文件里移除所有与 Swagger 相关的依赖包,例如:
```xml
<!-- pom.xml -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<!-- ...版本信息... -->
</dependency>
```
或者 Gradle 格式:
```groovy
// build.gradle
implementation 'io.springfox:springfox-boot-starter'
```
这样做会彻底禁用整个 Swagger 功能模块。
#### 2. 配置文件设置
如果只是想临时阻止通过浏览器打开 swagger-ui 页面而不完全删除库,则可以在 application.properties 或 application.yml 中添加如下的属性来限制其路径映射:
对于 `.properties` 文件来说就是这样的内容:
```properties
# application.properties
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
management.endpoints.web.exposure.include=*
springdoc.swagger-ui.enabled=false # 禁止swagger ui界面加载
```
如果是 YAML 文件则类似下面的样子:
```yaml
#application.yml
spring:
mvc:
pathmatch:
matching-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
management:
endpoints:
web:
exposure:
include: "*"
springdoc:
swagger-ui:
enabled: false # 禁止swagger ui界面加载
```
#### 3. 自定义 SecurityConfig 权限控制
为了更精细地管理谁能够看到你的API文档以及谁能操作那些资源,在很多场景下都会结合 spring security 使用自定义的安全策略来进行保护;你可以根据实际情况编写相应的拦截规则允许某些用户组查看而拒绝其他人的请求。
例如:
```java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 其他配置...
// 只有管理员角色才可以访问 /v2/api-docs 和 /swagger-ui/**
http.authorizeRequests()
.antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/security",
"/swagger-ui.html", "/webjars/**")
.hasRole("ADMIN")
.anyRequest().authenticated();
http.csrf().disable(); // 如果不需要csrf防护,可以选择性去掉
}
}
```
以上三种方法都可以有效地禁止外部非授权人员随意浏览到您的项目内部接口详情页,选择适合您当前应用场景的做法即可!
阅读全文
相关推荐



















