When working on APIs, secure endpoints often need an easy way to authorize requests during development and testing. Swagger (via Springdoc OpenAPI) lets us integrate JWT-based authentication directly into the UI. Here’s a breakdown of the configuration that makes this happen:
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.components.Components;
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;
import java.util.Collections;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.components(new Components()
.addSecuritySchemes("bearer-key",
new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")))
.addSecurityItem(new SecurityRequirement()
.addList("bearer-key", Collections.emptyList()));
}
}
Let’s break this down:
-
Components Section:
This part defines a new security scheme calledbearer-key
. It’s set toHTTP
type, with thebearer
scheme, andJWT
format. This makes Swagger show an “Authorize” button to input the token. -
SecurityRequirement Section:
This tells Swagger to attach the provided token to every request under the security schemebearer-key
. Without this, Swagger won’t send the token, even if you authorize.
This configuration makes life easier for developers working with secured endpoints — no need to manually add tokens to headers. Just authenticate once, and Swagger handles the rest.

