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:


3. Swagger Configuration

First, we need to configure the JWT SecurityScheme:

private SecurityScheme createAPIKeyScheme() {
    return new SecurityScheme().type(SecurityScheme.Type.HTTP)

And then, we configure our OpenAPI bean to include API info and security schemes:

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.")
    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:

swagger authorize


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:

swagger get clients


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.

Course – LSS (cat=Security/Spring Security)

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

res – Security (video) (cat=Security/Spring Security)
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.