SpringBoot整合Swagger頁面禁止訪問swagger-ui.html方式
SpringBoot整合Swagger頁面禁止訪問swagger-ui.html
在Spring Boot中禁止訪問Swagger UI頁面并在攔截器中進行攔截可以通過配置Spring Security來實現。
下面是一個簡單的示例,演示如何實現這一點:
在Spring Boot項目中創(chuàng)建一個Spring Security配置類
如下所示:
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/swagger-ui.html").denyAll() .antMatchers("/swagger-resources/**").permitAll() // 如果需要訪問Swagger的其他資源,可以放行 .and() .csrf().disable(); } }
在這個配置中,我們使用HttpSecurity
對象配置了訪問規(guī)則。
.antMatchers("/swagger-ui.html").denyAll()
表示禁止訪問swagger-ui.html
頁面- 而
.antMatchers("/swagger-resources/**").permitAll()
則允許訪問Swagger的其他資源
創(chuàng)建一個攔截器(Interceptor)類
用于攔截對 swagger-ui.html
的訪問:
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request.getRequestURI().equals("/swagger-ui.html")) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return false; // 攔截訪問 } return true; // 放行其他請求 } // 可以實現 postHandle 和 afterCompletion 方法進行相應處理 }
配置這個攔截器類并使其生效:
import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()); } }
這樣配置后,即可通過Spring Security和攔截器實現禁止訪問Swagger UI頁面 swagger-ui.html
。
如果你想完全禁用Swagger UI和Swagger資源
你可以在 Spring Boot 項目的 application.yml
或 application.properties
文件中添加以下配置來實現:
- 在
application.yml
文件中的配置:
spring: profiles: swagger: enabled: false
- 在
application.properties
文件中的配置:
spring.profiles.swagger.enabled=false
通過將這些配置設置為 false
,你可以完全禁用 Spring Boot 中關于 Swagger UI 和 Swagger 資源的自動配置和展示。
這樣就可以確保這些端點和頁面對外部用戶不可見或無法訪問。
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot項目啟動后自動加載系統(tǒng)配置的多種實現方式
這篇文章主要介紹了SpringBoot項目啟動后自動加載系統(tǒng)配置的多種實現方式,并通過代碼示例講解的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下2025-01-01Java 使用keytool創(chuàng)建CA證書的操作
這篇文章主要介紹了Java 使用keytool創(chuàng)建CA證書的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01Java實戰(zhàn)項目之校園跑腿管理系統(tǒng)的實現
只有理論是不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+Springboot+vue+maven+elementui+mysql實現一個校園跑腿管理系統(tǒng),大家可以在過程中查缺補漏,提升水平2022-01-01