Setting Up Swagger with JWT Authentication in Spring Boot

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:

  1. Components Section:
    This part defines a new security scheme called bearer-key. It’s set to HTTP type, with the bearer scheme, and JWT format. This makes Swagger show an “Authorize” button to input the token.
  2. SecurityRequirement Section:
    This tells Swagger to attach the provided token to every request under the security scheme bearer-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.

Popup
Button


Related Post