I have swagger plugged in to my spring boot application. Spring boot allows you to have property files for each environment that you have. Is there a way to disable swagger for a production environment?
We should not enable swagger in production due to security threats. In.net core version 6.0 version, we can protect it with the below code in Program.
You can change default swagger-ui path programmatically using ApplicationListener<ApplicationPreparedEvent> . The idea is simple - override springdoc. swagger-ui. path=/custom/path before your Spring Boot application starts.
Spring boot allows you to have property files for each environment that you have. Is there a way to disable swagger for a production environment? Put your swagger configuration into separate configuration class and annotate it with @Profile annotation -> so that it will be scanned into Spring context only in certain profiles.
To disable Swagger in production, let's toggle whether this configuration bean is injected. 3. Using Spring Profiles In Spring, we can use the @Profile annotation to enable or disable the injection of beans. Let's try using a SpEL expression to match the “swagger” profile, but not the “prod” profile:
/swagger-ui.html still available but there is no methods. Is there way to forbid URL ? I think this is more neater way of enabling swagger on demand, instead of disabling for some profiles.
Similarly, take care to defend the Swagger UI page against frame-jacking, e.g., via the X-Frame-Options header. Thanks for contributing an answer to Information Security Stack Exchange!
Put your swagger configuration into separate configuration class and annotate it with @Profile
annotation -> so that it will be scanned into Spring context only in certain profiles.
Example:
@Configuration @EnableSwagger2 @Profile("dev") public class SwaggerConfig { // your swagger configuration }
You can than define profile your Spring Boot app is operating in via command line: --spring.profiles.active=dev
or via config file: spring.profiles.active=dev
.
Read this section of Spring Boot docs for more info about @Profile
If you are working on multiple environments then you can also use @Profile as array
@Configuration @EnableSwagger2 @Profile({"dev","qa"}) public class SwaggerConfig { // your swagger configuration }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With