1. Introduction
In this short tutorial, we will see how to configure Swagger UI to include a JSON Web Token (JWT) when it calls our API.
2. Maven Dependencies
In this example, we’ll use springdoc-openapi-ui, which includes all the necessary dependencies to start working with Swagger and Swagger UI. Let’s add it to our pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.7.0</version>
</dependency>
3. Swagger Configuration
First, we need to configure the JWT SecurityScheme:
private SecurityScheme createAPIKeyScheme() {
return new SecurityScheme().type(SecurityScheme.Type.HTTP)
.bearerFormat("JWT")
.scheme("bearer");
}
And then, we configure our OpenAPI bean to include API info and security schemes:
@Bean
public OpenAPI openAPI() {
return new OpenAPI().addSecurityItem(new SecurityRequirement().
addList("Bearer Authentication"))
.components(new Components().addSecuritySchemes
("Bearer Authentication", createAPIKeyScheme()))
.info(new Info().title("My REST API")
.description("Some custom description of API.")
.version("1.0").contact(new Contact().name("Sallo Szrajbman")
.email( "www.baeldung.com").url("[email protected]"))
.license(new License().name("License of API")
.url("API license URL")));
}
4. REST Controller
In our ClientsRestController, let’s write a simple getClients endpoint to return a list of clients:
@RestController(value = "/clients")
@Tag(name = "Clients")
public class ClientsRestController {
@Operation(summary = "This method is used to get the clients.")
@GetMapping
public List<String> getClients() {
return Arrays.asList("First Client", "Second Client");
}
}
5. Swagger UI
When we start our application, we can access the Swagger UI at the http://localhost:8080/swagger-ui.html URL.
Here’s a look at the Swagger UI with Authorize button:
Swagger UI will ask for the JWT when we click the Authorize button.
We need to input our token and click on Authorize, and from then on, all the requests made to our API will automatically contain the token in the HTTP headers:
6. API Request with JWT
When sending the request to our API, we can see that there’s an “Authorization” header with our token value:
7. Conclusion
In this article, we saw how Swagger UI provides custom configurations to set up JWT, which can be helpful when dealing with our application authorization. After authorizing in Swagger UI, all the requests will automatically include our JWT.
The source code in this article is available on GitHub.