Documenting secured endpoints in Swagger UI
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)API docs that ignore security lie to their readers: every "Try it out" on ShopLite ends in 401, and nobody can tell which operations are public.
A bearer-JWT security scheme
A security scheme is the part of an OpenAPI document that names one way a client proves who it is. ShopLite has one: the access token from login, sent as a bearer token in the Authorization header.
Swagger UI needs to know how ShopLite checks callers. Example 1 adds the scheme and a default requirement in OpenApiConfig.
Example 1 · src/main/java/com/shoplite/common/OpenApiConfig.java (security scheme and default requirement)
Runs in: the shoplite-api Spring Boot project
@Configurationclass OpenApiConfig {
/** The name of the security scheme; operations refer to it in their "security" list. */ static final String BEARER_JWT = "bearer-jwt";
@Bean OpenAPI shopLiteOpenApi() { Components components = new Components(); // ... the error responses (ValidationFailed, NotFound, ...) as in Section 15
// One scheme: "Authorization: Bearer <access token>". Swagger UI shows an Authorize button for it. components.addSecuritySchemes(BEARER_JWT, new SecurityScheme() .type(SecurityScheme.Type.HTTP) .scheme("bearer") .bearerFormat("JWT") .description("The accessToken from POST /api/v1/auth/login. It expires after 15 minutes."));
return new OpenAPI() .info(new Info().title("ShopLite API").version("v1")) .components(components) // Every operation needs the token unless it says otherwise .addSecurityItem(new SecurityRequirement().addList(BEARER_JWT)); }}$ curl -s http://localhost:8080/v3/api-docs | jq -c '.components.securitySchemes, .security'
{"bearer-jwt":{"type":"http","description":"The accessToken from POST /api/v1/auth/login. It expires after 15 minutes.","scheme":"bearer","bearerFormat":"JWT"}}
[{"bearer-jwt":[]}]What this code does
addSecuritySchemesnames the schemebearer-jwt; the name is only a key that requirements refer to.addSecurityItemon theOpenAPIobject is the document's default: the top-levelsecuritylist in the JSON.- The empty array in
{"bearer-jwt":[]}is for OAuth scopes; bearer tokens have none.
In OpenAPI the scheme is type: http, scheme: bearer and bearerFormat: JWT; the format is only a hint for readers. A security requirement says which scheme an operation needs, and the one added at the top of the document is the default for every operation. ShopLite builds both with springdoc-openapi 3.1.1, the version for Spring Boot 4.
The docs only describe the security; SecurityConfig still decides who may call what. When the two disagree the docs are wrong, which is why ShopLite checks them in ApiDocsIT.
Public and secured operations
A security requirement says which security scheme an operation needs. An empty list, security: [], means the operation is public and needs no token.
With a default requirement, every operation shows a padlock. Example 2 marks the public ones with an empty @SecurityRequirements.
Example 2 · Marking public operations with @SecurityRequirements
Runs in: the shoplite-api Spring Boot project
@Tag(name = "Sign-in", description = "Sign up, log in, refresh the tokens and log out")@SecurityRequirements // empty: these operations do not need the bearer token@RestController@RequestMapping("/api/v1/auth")class AuthController { // register, login, refresh, logout ...}
@SecurityRequirements@Operation(operationId = "listProducts", summary = "Search products, one page at a time")@GetMappingPageResponse<ProductResponse> list(/* filters, page, size, sort */) { ... }
@Operation(operationId = "createProduct", summary = "Create a product") // no annotation: secured@PostMappingResponseEntity<ProductResponse> create(@Valid @RequestBody CreateProductRequest request) { ... }$ curl -s http://localhost:8080/v3/api-docs | jq -c '.paths["/api/v1/products"].get.security, .paths["/api/v1/auth/login"].post.security, .paths["/api/v1/me/orders"].get.security' [] [] null
What this code does
- Search products and login print
[]: an empty list, so Swagger UI shows no padlock and sends no token. GET /api/v1/me/ordersprintsnull: the operation has no list of its own, so the document's default (bearer-jwt) applies.- On
AuthControllerthe annotation sits on the class, so register, login, refresh and logout are all public.
ShopLite marks exactly the operations that SecurityConfig permits for guests: the four /api/v1/auth/... endpoints and the GET operations on products and categories. On a class, @SecurityRequirements covers every method in the controller. The other annotation, @SecurityRequirement(name = "bearer-jwt"), adds a requirement to one operation; it is needed only when there is no default, and ShopLite has one.
Three rules cover every case:
- Default requirement in
OpenApiConfig: every operation needsbearer-jwt. @SecurityRequirements(empty) on a method or class: public,security: [].- No annotation: the default applies, and the operation has no
securityfield in the JSON.
Predict the output
Public or secured in the docs?
Pick what the docs JSON shows for security on each operation.
Round 1 of 3
A product search with an empty annotation.
The Authorize button
The Authorize button is Swagger UI's dialog that stores a token you paste in and sends it on every secured operation.
Swagger UI shows Authorize once the document has a security scheme. Example 3 shows the requests behind it; Example 4 opens the token you paste.
Example 3 · What Swagger UI sends before and after Authorize
Runs in: the shoplite-api Spring Boot project
# 1. "Try it out" on POST /api/v1/auth/login sends this request$ curl -X POST http://localhost:8080/api/v1/auth/login -H "Content-Type: application/json" \ -d '{"email":"asha.rao@example.com","password":"asha-dev-password"}'# 2. After Authorize, every secured operation adds the header$ curl "http://localhost:8080/api/v1/me/orders?size=2" -H "Authorization: Bearer $ASHA"# 3. Without Authorize (or after Logout in the dialog)$ curl -i http://localhost:8080/api/v1/me/orders{"accessToken":"eyJraWQiOiJNNmZCajNFamtGWDZQT3BWMnpsc0tWdXJvNUJGOGtITXRBNUNndWdmVUZVIiwiYWxnIjoiSFMyNTYifQ.eyJpc3MiOiJzaG9wbGl0ZS1hcGkiLCJjdXN0b21lcklkIjoxLCJzdWIiOiIyIiwiZXhwIjoxNzkyMTQzMTM3LCJpYXQiOjE3OTIxNDIyMzcsInJvbGVzIjpbIkNVU1RPTUVSIl19.mn0dWURFLQVc9IFF-cVshRgTte_tnI8-O370Kkw2Ick","tokenType":"Bearer","expiresIn":900,"refreshToken":"lhPwuxvMRDx1htax3NrJEGycTjcL_LB_ekNrr0e9B0c"}
{"content":[{"id":10,"customerId":1,"status":"DELIVERED","orderedAt":"2026-08-30T12:25:00+05:30","total":4398.00},{"id":3,"customerId":1,"status":"DELIVERED","orderedAt":"2026-07-18T13:05:00+05:30","total":43839.00}],"page":0,"size":2,"totalElements":3,"totalPages":2}
HTTP/1.1 401
WWW-Authenticate: Bearer resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
Content-Type: application/problem+json
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"Sign in to use this endpoint.","instance":"/api/v1/me/orders"}What this code does
- The login answer is the same JSON you see in Swagger UI's response box;
accessTokenis what goes into Authorize (tokens are different on every login). - With the token,
/api/v1/me/ordersreturns only Asha's orders: the customer id comes from the token, not from the request. - Without it, the 401 has Spring's standard
WWW-Authenticate: Bearer ...header and ShopLite'sunauthorizedproblem body.
Example 4 · What the Authorize box holds: decoding a token's payload
import java.nio.charset.StandardCharsets;import java.util.Base64;
public class TokenPayloadDemo { // The accessToken from POST /api/v1/auth/login for Asha (dev account), as pasted into Authorize static final String TOKEN = "eyJraWQiOiJNNmZCajNFamtGWDZQT3BWMnpsc0tWdXJvNUJGOGtITXRBNUNndWdmVUZVIiwiYWxnIjoiSFMyNTYifQ" + ".eyJpc3MiOiJzaG9wbGl0ZS1hcGkiLCJjdXN0b21lcklkIjoxLCJzdWIiOiIyIiwiZXhwIjoxNzkyMTQzMTM3LCJpYXQiOjE3OTIxNDIyMzcsInJvbGVzIjpbIkNVU1RPTUVSIl19" + ".mn0dWURFLQVc9IFF-cVshRgTte_tnI8-O370Kkw2Ick";
static String decode(String part) { return new String(Base64.getUrlDecoder().decode(part), StandardCharsets.UTF_8); }
public static void main(String[] args) { String[] parts = TOKEN.split("\\."); System.out.println("Parts: " + parts.length); System.out.println("Header: " + decode(parts[0])); System.out.println("Payload: " + decode(parts[1])); System.out.println("Swagger UI sends: Authorization: Bearer " + TOKEN.substring(0, 20) + "..."); }}Parts: 3
Header: {"kid":"M6fBj3EjkFX6POpV2zlsKVuro5BF8kHMtA5CgugfUFU","alg":"HS256"}
Payload: {"iss":"shoplite-api","customerId":1,"sub":"2","exp":1792143137,"iat":1792142237,"roles":["CUSTOMER"]}
Swagger UI sends: Authorization: Bearer eyJraWQiOiJNNmZCajNF...What this code does
- A JWT is three Base64URL parts joined by dots; the first two are plain JSON that anyone can read, so tokens never hold secrets.
subis the user id (Asha is user 2),customerIdis 1 andexp - iatis 900 seconds: the 15 minutes Swagger UI's token lasts.- Reading the payload proves nothing: only the server's
JwtDecoder, with the secret key, can check the signature in the third part.
From then on Swagger UI adds Authorization: Bearer ... to every secured operation, and public ones are sent without it. After 15 minutes the token expires and calls answer 401 again: log in once more, or swap the refresh token at POST /api/v1/auth/refresh.
By default Swagger UI keeps the token only in the open page, so a reload forgets it. The setting springdoc.swagger-ui.persist-authorization=true keeps it in the browser's local storage, which is handy but lets any script on that page read it. ShopLite leaves it off. In dev the steps are:
- Open
http://localhost:8080/swagger-ui.htmlin the dev profile. - Run "Try it out" on
POST /api/v1/auth/loginwith a dev account and copyaccessTokenwithout quotes. - Press Authorize, paste the token and close the dialog; then call
GET /api/v1/me/ordersfor 200.
Order of execution
Call a secured operation
Tap the steps in the order you do them in Swagger UI.
Documenting 401, 403 and 409
A reusable response is an entry under components.responses that operations point to by name, so the same error is described once.
ShopLite writes each security error once, with a ProblemDetail example that matches the real body. Example 5 defines them and adds them to every secured operation.
Example 5 · Reusable 401, 403 and 409 responses and the OpenApiCustomizer
Runs in: the shoplite-api Spring Boot project
components.addResponses("Unauthorized", problem("No access token, or one that is invalid or expired", example("unauthorized", "Unauthorized", 401, "Sign in to use this endpoint.", "/api/v1/me/orders", null)));components.addResponses("Forbidden", problem("Signed in, but your role does not allow this", example("forbidden", "Forbidden", 403, "You do not have permission to do this.", "/api/v1/products", null)));components.addResponses("EmailTaken", problem("An account with this e-mail already exists", example("already-exists", "Resource already exists", 409, "An account with e-mail asha.rao@example.com already exists.", "/api/v1/auth/register", null)));
// ... and one bean that adds 401 and 403 to every operation that needs a token@BeanOpenApiCustomizer securityResponses() { return openApi -> openApi.getPaths().values().forEach(path -> path.readOperations().forEach(operation -> { if (operation.getSecurity() != null && operation.getSecurity().isEmpty()) { return; // public operation: no 401 or 403 } ApiResponses responses = operation.getResponses(); responses.putIfAbsent("401", new ApiResponse().$ref("#/components/responses/Unauthorized")); responses.putIfAbsent("403", new ApiResponse().$ref("#/components/responses/Forbidden")); }));}
@ApiResponse(responseCode = "201", description = "Created; Location points to the new customer")@ApiResponse(responseCode = "400", ref = "ValidationFailed")@ApiResponse(responseCode = "409", ref = "EmailTaken")@PostMapping("/register")$ curl -s http://localhost:8080/v3/api-docs | jq -c '(.paths["/api/v1/products"].post.responses | keys), (.paths["/api/v1/products"].get.responses | keys), (.paths["/api/v1/auth/register"].post.responses | keys)'
["201","400","401","403","409","422"]
["200","400"]
["201","400","409"]
$ curl -s http://localhost:8080/v3/api-docs | jq -c '.components.responses.Forbidden.content["application/problem+json"].example'
{"type":"https://shoplite.example/problems/forbidden","title":"Forbidden","status":403,"detail":"You do not have permission to do this.","instance":"/api/v1/products"}What this code does
- Creating a product is secured, so the customizer added 401 and 403 next to the operation's own 201, 400, 409 and 422.
- Searching products and signing up are public: no 401 or 403, and sign-up documents its 409
EmailTakenitself. - The
Forbiddenexample is the exact bodySecurityProblemswrites, so the docs and the real 403 match field for field.
Section 15 added ValidationFailed, NotFound and AlreadyExists; the security section adds Unauthorized (401), Forbidden (403), LoginFailed (401 at login), TooManyRequests (429) and EmailTaken (409 at sign-up).
Writing @ApiResponse(responseCode = "401", ref = "Unauthorized") on forty methods is easy to forget, so ShopLite adds one OpenApiCustomizer bean. springdoc calls it after building the document, and it adds 401 and 403 to every operation whose security list is not empty. Public operations document only their own errors, such as 409 EmailTaken on sign-up.
Find the bug
Find the wrong line in the docs
Each snippet documents an error badly. Tap the wrong line.
The 403 example in the Forbidden response.
Round 1 of 3putIfAbsent keeps any 401 or 403 an operation documents itself, for example LoginFailed on the login operation.Swagger UI in dev and prod
In dev the docs are a tool for the team; in prod they are a public map of the API. Example 6 shows the properties and how each profile answers.
Example 6 · Docs on in dev, off in prod
Runs in: the shoplite-api Spring Boot project
# src/main/resources/application-prod.properties# No API docs or Swagger UI in productionspringdoc.api-docs.enabled=falsespringdoc.swagger-ui.enabled=false# src/main/resources/application.properties (all profiles): only /api/v1/** goes into the docsspringdoc.paths-to-match=/api/v1/**# SecurityConfig keeps the docs URLs public, so dev needs no token to open Swagger UI:# .requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()# dev profile
$ curl -s -o /dev/null -w "%{http_code} %{redirect_url}\n" http://localhost:8080/swagger-ui.html
302 http://localhost:8080/swagger-ui/index.html
# prod profile (java -jar target/shoplite-api-1.1.0.jar --spring.profiles.active=prod)
$ curl -i http://localhost:8080/v3/api-docs
HTTP/1.1 404
{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"There is no endpoint GET /v3/api-docs.","instance":"/v3/api-docs"}
$ curl -i http://localhost:8080/swagger-ui.html
HTTP/1.1 404
{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"There is no endpoint GET /swagger-ui.html.","instance":"/swagger-ui.html"}What this code does
- In dev,
/swagger-ui.htmlredirects to the UI page, and no token is needed to open it. - In prod springdoc registers no docs endpoints, so the request reaches the normal "no such endpoint" handling and answers ShopLite's 404 problem.
- The URL rules can stay the same in every profile; the properties decide whether the docs exist.
In dev, SecurityConfig permits /v3/api-docs/**, /swagger-ui/** and /swagger-ui.html without a token: opening the page needs no sign-in, but calling a secured operation still needs Authorize. In prod ShopLite switches springdoc off in application-prod.properties, so those URLs do not exist and answer the contract's 404. A staging server that needs the docs keeps them on and changes the permitAll() for the docs URLs to hasRole("ADMIN").
Turning the docs off hides nothing that matters for security, because the rules live in SecurityConfig. It only removes an easy guide to the API for attackers.
Fix the error
Switch the docs off in prod
In prod, GET /v3/api-docs still answers. Pick the replacement for the highlighted line.
Both docs endpoints must disappear in the prod profile.
Error
GET /v3/api-docs -> HTTP/1.1 200 (expected 404 in prod)
Next step
Check your understanding
12 quick questions