Sub topic 11
Documenting bearer token authentication
What this chapter assumes
You should have springdoc-openapi running in a Spring Boot 3 project, so /v3/api-docs and Swagger UI already respond. You should also know the basic OpenAPI annotations from the earlier chapters (@Operation, @Tag) and how a bearer token travels in an Authorization header. The chapter does not cover how your application validates tokens. It covers how to describe the authentication so readers and Swagger UI can use it.
Documentation is separate from enforcement
springdoc reads your controllers and annotations and writes a description. It does not read your Spring Security configuration to find out which endpoints need a token. If you protect /api/** with Spring Security but add no security metadata, the generated document shows every endpoint as open. Swagger UI then sends requests with no Authorization header and you get 401 Unauthorized.
So you need two things:
- A named security scheme, which says what kind of credential exists (here, an HTTP bearer token carrying a JWT).
- A security requirement, which says which operations need that scheme.
The diagram shows how these pieces interact when someone uses Swagger UI.
Declaring the scheme with annotations
The @SecurityScheme annotation defines a scheme and gives it a name. Place it on any Spring-scanned class. A configuration class is a common choice.
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import org.springframework.context.annotation.Configuration;
@Configuration
@OpenAPIDefinition(info = @Info(title = "Library API", version = "1.0.0"))
@SecurityScheme(
name = "bearerAuth",
type = SecuritySchemeType.HTTP,
scheme = "bearer",
bearerFormat = "JWT")
public class OpenApiSecurityConfig {
}These attributes matter:
| Attribute | Meaning |
|---|---|
| `name` | The key other annotations use to refer to this scheme. It is not shown as a header name. |
| `type` | `HTTP` means the credential goes in the standard `Authorization` header. |
| `scheme` | `bearer` selects the "Bearer" authorization scheme. |
| `bearerFormat` | A hint for readers, such as `JWT`. Tools do not validate it. |
Because the type is HTTP with scheme bearer, Swagger UI shows a single text box for the token and adds the Bearer prefix itself. Users paste only the token, not the word Bearer.
Declaring the scheme with an OpenAPI bean
If you already build an OpenAPI bean, you can declare the scheme there instead of using annotations. The result in the generated document is the same.
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenApiBeanSecurityConfig {
private static final String SCHEME_NAME = "bearerAuth";
@Bean
public OpenAPI libraryOpenApi() {
return new OpenAPI()
.info(new Info().title("Library API").version("1.0.0"))
.components(new Components().addSecuritySchemes(SCHEME_NAME,
new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")))
.addSecurityItem(new SecurityRequirement().addList(SCHEME_NAME));
}
}The last line, addSecurityItem, is a global requirement. It marks every operation as needing bearerAuth. Use either this bean or the annotation class above, not both with the same scheme name, or you will define the same scheme twice.
Applying the requirement to operations
Declaring a scheme does not protect or mark anything yet. A requirement does that. With the annotation approach, @SecurityRequirement can go on a whole controller or on a single method.
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/books")
@Tag(name = "Books", description = "Operations on the book catalog")
public class BookAdminController {
private final BookService service;
public BookAdminController(BookService service) {
this.service = service;
}
@Operation(summary = "Delete a book")
@SecurityRequirement(name = "bearerAuth")
@DeleteMapping("/{id}")
public void delete(@PathVariable long id) {
service.deleteById(id);
}
}The name must match the scheme name exactly. A typo does not fail at startup. The operation just lists a requirement for a scheme that does not exist, and Swagger UI may show no lock icon or no usable Authorize option.
Putting @SecurityRequirement(name = "bearerAuth") on the class applies it to every method in that controller. This is the usual choice when a whole controller sits behind authentication.
Opting out of a global requirement
If you use the global addSecurityItem, you will have a few public endpoints, such as login or a health check. Mark those with an empty @SecurityRequirements annotation (plural), which overrides the global rule for that operation.
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/status")
public class StatusController {
@Operation(summary = "Public status check")
@SecurityRequirements
@GetMapping
public String status() {
return "ok";
}
}In the generated document this operation gets "security": [], which means "no authentication required".
What the generated document contains
Fetch /v3/api-docs and look for two places. The scheme appears once under components, and each protected operation points to it.
{
"components": {
"securitySchemes": {
"bearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
},
"paths": {
"/api/books/{id}": {
"delete": {
"summary": "Delete a book",
"security": [ { "bearerAuth": [] } ]
}
}
}
}The empty array after bearerAuth lists OAuth scopes. Bearer tokens have none in this model, so it stays empty.
Using the Authorize button
Once at least one scheme exists, Swagger UI shows an Authorize button at the top. Operations with a requirement show a lock icon. To try a protected call:
- Click Authorize.
- Paste the raw token into the
bearerAuthvalue field and confirm. - Expand an operation, choose Try it out, and run it.
The UI now sends Authorization: Bearer <token> on every operation that lists the scheme. Reloading the page forgets the token. To keep it across reloads during development, set springdoc.swagger-ui.persist-authorization: true. This stores the token in the browser's local storage, so avoid it on a shared machine.
Keeping the docs reachable under Spring Security
Spring Security blocks /v3/api-docs and the Swagger UI assets like any other URL. If they return 401 or redirect to a login page, allow them explicitly.
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();
}
}This rule opens only the documentation. The API endpoints still need a valid token, and actual token validation comes from other configuration, such as an OAuth2 resource server. Leaving the docs open is convenient in development. The production chapter covers restricting or removing this rule.
Common errors
- Swagger UI returns 401 on every call. The operation has no
@SecurityRequirement, so Swagger UI never sends the header. Add a requirement or a global item. - No Authorize button. No scheme is declared, or the class holding
@SecuritySchemeis not a Spring-scanned component. - Token rejected after pasting
Bearer eyJ.... Swagger UI adds the prefix for HTTP bearer schemes, so you sentBearer Bearer eyJ.... Paste only the token. - Lock icon missing on one endpoint. Check the scheme name for typos, and check whether an empty
@SecurityRequirementsoverrides a global requirement. - The docs themselves return 401. Add the
permitAll()rule above, or log in before opening the UI.
Exercise
Your API declares @SecurityScheme(name = "bearerAuth", ...), and Swagger UI shows an Authorize button. Calls to GET /api/orders still go out without an Authorization header. What is the likely cause, and what are two ways to fix it?
Show answer
The scheme is declared, but no operation references it, so Swagger UI has no requirement to apply. Fix it by adding @SecurityRequirement(name = "bearerAuth") to the controller or method. Alternatively, add a global requirement with new OpenAPI().addSecurityItem(new SecurityRequirement().addList("bearerAuth")) and opt out public endpoints with @SecurityRequirements.
Exercise
A public login endpoint sits in an API that uses a global bearer requirement. How do you document it as unauthenticated, and what does the generated JSON show for that operation?
Show answer
Annotate the method with an empty @SecurityRequirements. The generated operation contains "security": [], which overrides the global requirement and marks the endpoint as needing no authentication.
Exercise
A teammate pastes Bearer eyJhbGciOi... into the Authorize dialog and gets 401. Why, and what should they paste?
Show answer
For an HTTP bearer scheme, Swagger UI prepends Bearer itself, so the header becomes Bearer Bearer eyJ.... They should paste only the token, eyJhbGciOi....