Sub topic 14
Protecting or disabling the docs in production
This chapter assumes you can build Spring Boot 3 REST controllers, you have springdoc-openapi on the classpath, and you know the basics of Spring Security's SecurityFilterChain and Spring profiles. By the end you will be able to decide whether your API description should be public, protected or switched off, and apply that decision in configuration.
Why the docs are a security concern
The OpenAPI document lists every path, parameter, request body, response shape and security scheme in your API. Swagger UI turns that list into a page where anyone can send requests. Neither one is a vulnerability by itself. Both give an attacker a free map of your attack surface, including internal endpoints you forgot to hide.
You have three realistic options:
| Option | When it fits | Cost |
|---|---|---|
| Leave public | The API is public by design and the docs are part of the product | Exposes details of every documented endpoint |
| Require authentication | Only internal staff or partners need the docs | You must maintain a security rule and a way to sign in |
| Disable | Nobody needs live docs on that environment | Consumers need the specification delivered another way |
Choose per environment. A common pattern is open docs in development, authenticated docs in staging and no docs in production.
What needs protecting
Springdoc registers two groups of endpoints, and a security rule has to cover both.
- The JSON description at
/v3/api-docs, plus/v3/api-docs/{group}for eachGroupedOpenApibean and/v3/api-docs.yamlfor the YAML form. - The Swagger UI page at
/swagger-ui.html, which redirects to/swagger-ui/index.html, together with its static assets under/swagger-ui/**.
Protecting only the UI page leaves the JSON open, and the JSON contains everything the UI shows. If you changed the paths with springdoc.api-docs.path or springdoc.swagger-ui.path, your security rules must use the new paths.
Option 1: permit the docs while developing
If Spring Security is on the classpath, every endpoint is protected by default, including the docs. Swagger UI then fails to load its description. A rule that lets the documentation through looks like this:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()
.anyRequest().authenticated());
return http.build();
}
}Note that /v3/api-docs/** matches /v3/api-docs/public and other group documents, but the pattern with /** also matches the bare /v3/api-docs path in Spring Security's path matcher. The /swagger-ui.html entry is separate because it is a file-like path, not a child of /swagger-ui/.
This configuration is fine for a laptop or a private test environment. In production it makes the full API description public, so treat it as a development setting.
Option 2: require authentication or a role
To keep the docs available but restricted, replace permitAll() with a rule that checks for a role. This example keeps the API itself behind normal authentication and limits the docs to administrators:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class DocsSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html")
.hasRole("DOCS_READER")
.anyRequest().authenticated())
.httpBasic(basic -> { });
return http.build();
}
}HTTP Basic is used here so a browser can prompt for credentials and then load the UI and its JSON request with the same login. If your API uses bearer tokens only, a browser cannot easily attach a token when it navigates to /swagger-ui.html. In that case, put the docs behind a separate filter chain that uses Basic or a session login, and keep the token chain for /api/**. Use securityMatcher(...) on each chain and @Order to make the more specific one run first.
A common failure
If Swagger UI opens but shows "Failed to load API definition", the page itself was allowed through while /v3/api-docs was not. Open the browser's network tab and look for a 401 or 403 on the JSON request. Add the missing matcher, or check that the path in your rule matches the configured path.
Option 3: disable the docs per profile
Switching the endpoints off removes them from the application. Requests then receive a 404, because nothing is mapped. Put the properties in a profile-specific file:
# application-prod.yml
springdoc:
api-docs:
enabled: false
swagger-ui:
enabled: falseSpring Boot loads application-prod.yml when the prod profile is active, for example with SPRING_PROFILES_ACTIVE=prod. The two properties are independent:
springdoc.api-docs.enabled=falseturns off the JSON and YAML endpoints. This also stops Swagger UI from working, because the UI has nothing to load.springdoc.swagger-ui.enabled=falseturns off only the UI page. The JSON stays available.
Setting both is clearer than relying on the first to imply the second. It also means the intent survives if someone later re-enables one of them.
Springdoc also has springdoc.api-docs.enabled as a single switch that prevents the library from scanning your controllers at runtime. With the document disabled, you avoid the startup and first-request cost of building it.
Verify, do not assume
A setting that is spelled wrong does nothing and fails silently. After you build the production configuration, check it:
- Start the application with the
prodprofile. - Request
/v3/api-docsand/swagger-ui.html. - Confirm both return 404, or 401 if you used a security rule.
An automated check is better than a manual one. The test below fails the build if the docs are reachable under the prod profile:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("prod")
class DocsDisabledInProdTest {
@Autowired
private MockMvc mockMvc;
@Test
void apiDocsAreNotExposed() throws Exception {
mockMvc.perform(get("/v3/api-docs")).andExpect(status().isNotFound());
}
@Test
void swaggerUiIsNotExposed() throws Exception {
mockMvc.perform(get("/swagger-ui.html")).andExpect(status().isNotFound());
}
}If Spring Security is present, an unauthenticated request may get a 401 before the 404 is produced, because the filter chain runs before routing. In that case assert the status your security setup returns, or send authenticated requests in the test.
Related controls
Disabling the docs hides the description but does not secure the API. Anyone who knows or guesses a URL can still call it. Keep authorization on the endpoints themselves.
- Use
springdoc.paths-to-matchor@Hiddento keep internal endpoints out of the document even in environments where it is visible. - Remove example values that contain real data, such as real e-mail addresses or tokens, from
@Schema(example = ...). - If you need production consumers to read the specification, generate it at build time and publish the file as an artifact or on a documentation site, instead of exposing the live endpoint.
Choosing a policy
- Public API with external developers: publish the docs, ideally as a static artifact, and keep the live endpoint disabled.
- Internal API behind a gateway: allow the docs for a role such as
DOCS_READER, or only from the internal network. - Anything else: disable in
prod, enable indevandtestprofiles.
Exercise
Your prod profile sets springdoc.swagger-ui.enabled=false and nothing else. A security scan still downloads the full API description. Which request returned it, and what change closes the gap?
Show answer
The scan requested /v3/api-docs (or /v3/api-docs.yaml). Disabling only Swagger UI leaves the JSON endpoint active. Set springdoc.api-docs.enabled=false in application-prod.yml as well, or protect /v3/api-docs/** with a security rule, and then confirm with a request under the prod profile that it no longer returns the document.
Exercise
Swagger UI loads in your staging environment but displays "Failed to load API definition". Your security rule only permits /swagger-ui/**. What is wrong and how do you fix it?
Show answer
The UI page and its assets are allowed, but the browser's request for /v3/api-docs is rejected with 401 or 403. Add /v3/api-docs/** to the requestMatchers rule (with the same authorization requirement as the UI), and use the configured path if you changed springdoc.api-docs.path.