Spring MVC with Swagger Integration: Customizing Swagger UI and Adding Security

This blog shows you how to customize Swagger UI and add security to your Spring MVC RESTful API using basic authentication and Spring Security.

1. Introduction

In this tutorial, you will learn how to integrate Swagger with Spring MVC to document and test your RESTful API. You will also learn how to customize the Swagger UI to match your branding and add security to protect your API from unauthorized access.

Swagger is a popular tool for designing, documenting, and testing RESTful APIs. It provides a web-based interface that allows you to interact with your API and view its specifications. Swagger also generates documentation that is easy to read and understand for both developers and users.

Spring MVC is a framework for building web applications using the Model-View-Controller pattern. It supports the development of RESTful APIs that can handle various types of requests and responses. Spring MVC also provides features such as validation, exception handling, and data binding.

By integrating Swagger with Spring MVC, you can benefit from both tools and create a powerful and user-friendly API. You can also customize the Swagger UI to make it more appealing and consistent with your application’s style. Moreover, you can add security to your Swagger UI and your API endpoints using basic authentication and Spring Security.

To follow this tutorial, you need to have some basic knowledge of Java, Spring MVC, and RESTful APIs. You also need to have the following tools installed on your system:

  • Java Development Kit (JDK) 8 or higher
  • Maven 3.6 or higher
  • An IDE of your choice (such as Eclipse or IntelliJ IDEA)
  • A web browser (such as Chrome or Firefox)

Are you ready to get started? Let’s begin by setting up Spring MVC and Swagger in the next section.

2. Setting up Spring MVC and Swagger

In this section, you will learn how to set up Spring MVC and Swagger in your project. You will create a simple Spring MVC application that exposes a RESTful API for managing books. You will also add Swagger dependencies and configure Swagger annotations to document your API.

To create a Spring MVC application, you can use the Spring Initializr tool. It allows you to generate a Maven project with the required dependencies and configuration. You can choose the following options:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.5.6
  • Project Metadata: Group: com.example, Artifact: spring-swagger, Name: spring-swagger, Description: Demo project for Spring MVC and Swagger integration, Package name: com.example.spring.swagger
  • Dependencies: Spring Web, Spring Data JPA, H2 Database

After generating the project, you can import it into your IDE and explore the structure. You will see the following files and folders:

  • src/main/java: This folder contains the Java source code of your application.
  • src/main/resources: This folder contains the application properties and other resources.
  • src/test/java: This folder contains the test code of your application.
  • pom.xml: This file contains the Maven configuration and dependencies of your project.

To add Swagger dependencies to your project, you need to modify the pom.xml file and include the following:

<!-- Swagger dependencies -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>

These dependencies will enable the Swagger support and the Swagger UI in your application. You can also specify the Swagger version according to your preference.

To configure Swagger annotations in your application, you need to annotate your controller classes and methods with the appropriate annotations. For example, you can use the following annotations:

  • @Api: This annotation marks a class as a Swagger resource.
  • @ApiOperation: This annotation describes an operation or a method in the API.
  • @ApiParam: This annotation describes a parameter in the API.
  • @ApiResponse: This annotation describes a response from the API.

Here is an example of a controller class that uses these annotations:

package com.example.spring.swagger.controller;

import com.example.spring.swagger.model.Book;
import com.example.spring.swagger.service.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/books")
@Api(value = "Book Controller", description = "This controller manages the books in the system")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping
    @ApiOperation(value = "Get all books", response = Book.class, responseContainer = "List")
    public ResponseEntity<List> getAllBooks() {
        return ResponseEntity.ok(bookService.getAllBooks());
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "Get a book by id", response = Book.class)
    @ApiResponse(code = 404, message = "Book not found")
    public ResponseEntity getBookById(@PathVariable @ApiParam(value = "The id of the book", required = true) Long id) {
        Book book = bookService.getBookById(id);
        if (book == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(book);
    }

    @PostMapping
    @ApiOperation(value = "Create a new book", response = Book.class)
    public ResponseEntity createBook(@RequestBody @ApiParam(value = "The book to be created", required = true) Book book) {
        return ResponseEntity.status(HttpStatus.CREATED).body(bookService.createBook(book));
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "Update an existing book", response = Book.class)
    @ApiResponse(code = 404, message = "Book not found")
    public ResponseEntity updateBook(@PathVariable @ApiParam(value = "The id of the book to be updated", required = true) Long id,
                                           @RequestBody @ApiParam(value = "The book to be updated", required = true) Book book) {
        Book updatedBook = bookService.updateBook(id, book);
        if (updatedBook == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(updatedBook);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "Delete a book by id")
    @ApiResponse(code = 404, message = "Book not found")
    public ResponseEntity deleteBook(@PathVariable @ApiParam(value = "The id of the book to be deleted", required = true) Long id) {
        boolean deleted = bookService.deleteBook(id);
        if (!deleted) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.noContent().build();
    }
}

By using these annotations, you can provide more information and details about your API to the Swagger UI. You can also customize the annotations according to your needs.

Now that you have set up Spring MVC and Swagger in your project, you can run your application and access the Swagger UI at http://localhost:8080/swagger-ui/.

You can explore the API documentation and test the API endpoints using the Swagger UI. You can also modify the API and see the changes reflected in the Swagger UI.

In the next section, you will learn how to customize the Swagger UI to change the logo and title.

2.1. Adding Swagger dependencies

In this subsection, you will learn how to add the necessary dependencies to enable Swagger support and the Swagger UI in your Spring MVC project. You will modify the pom.xml file and include the springfox-boot-starter and springfox-swagger-ui dependencies.

The springfox-boot-starter dependency provides the core functionality of Swagger, such as generating the API documentation and exposing the Swagger endpoints. The springfox-swagger-ui dependency provides the web-based interface that allows you to view and test your API using the Swagger UI.

To add these dependencies, you need to open the pom.xml file in your IDE and locate the <dependencies> section. Then, you need to add the following code snippets inside the <dependencies> section:

<!-- Swagger dependencies -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>

These code snippets specify the groupId, artifactId, and version of the Swagger dependencies. You can also change the version according to your preference, as long as it is compatible with your Spring Boot version.

After adding these dependencies, you need to save the pom.xml file and let Maven update the project. You can also run the mvn clean install command in your terminal to ensure that the dependencies are downloaded and installed properly.

By adding these dependencies, you have enabled the Swagger support and the Swagger UI in your project. You can now proceed to the next subsection, where you will learn how to configure Swagger annotations in your controller classes and methods.

2.2. Configuring Swagger annotations

In this subsection, you will learn how to configure Swagger annotations in your controller classes and methods. You will use the appropriate annotations to provide more information and details about your API to the Swagger UI. You will also customize the annotations according to your needs.

Swagger annotations are Java annotations that you can use to annotate your controller classes and methods. They allow you to describe various aspects of your API, such as the resource name, the operation description, the parameters, the responses, and the error codes. By using these annotations, you can make your API documentation more clear and comprehensive.

Some of the common Swagger annotations that you can use are:

  • @Api: This annotation marks a class as a Swagger resource. You can use it to specify the value and the description of the resource.
  • @ApiOperation: This annotation describes an operation or a method in the API. You can use it to specify the value, the response, and the response container of the operation.
  • @ApiParam: This annotation describes a parameter in the API. You can use it to specify the value, the name, the type, and the required status of the parameter.
  • @ApiResponse: This annotation describes a response from the API. You can use it to specify the code and the message of the response.

To use these annotations, you need to import them from the io.swagger.annotations package. You also need to place them above the corresponding controller class or method. For example, you can use the following annotations to document the getBookById method in the BookController class:

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;

...

@RestController
@RequestMapping("/api/books")
@Api(value = "Book Controller", description = "This controller manages the books in the system")
public class BookController {

    ...

    @GetMapping("/{id}")
    @ApiOperation(value = "Get a book by id", response = Book.class)
    @ApiResponse(code = 404, message = "Book not found")
    public ResponseEntity getBookById(@PathVariable @ApiParam(value = "The id of the book", required = true) Long id) {
        Book book = bookService.getBookById(id);
        if (book == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(book);
    }

    ...

}

By using these annotations, you can provide more information and details about your API to the Swagger UI. You can also customize the annotations according to your needs. For example, you can add more @ApiResponse annotations to specify different error codes, or you can use the notes attribute to add more comments to the annotations.

After configuring the Swagger annotations, you need to restart your application and refresh the Swagger UI. You will see the updated API documentation and the additional information that you have provided. You can also test the API endpoints using the Swagger UI and see the responses and the error codes.

In the next section, you will learn how to customize the Swagger UI to change the logo and the title.

3. Customizing Swagger UI

In this section, you will learn how to customize the Swagger UI to change the logo and the title. You will also learn how to add custom CSS and JavaScript to modify the appearance and the behavior of the Swagger UI. You will use the springfox-swagger-ui dependency and the SwaggerConfig class to achieve these customizations.

The springfox-swagger-ui dependency provides the web-based interface that allows you to view and test your API using the Swagger UI. It also provides some configuration options that you can use to customize the Swagger UI. For example, you can change the logo and the title of the Swagger UI by using the apiInfo method in the SwaggerConfig class.

The SwaggerConfig class is a Java class that you can create in your project to configure the Swagger settings. You can use the @Configuration and @EnableSwagger2 annotations to mark this class as a Spring configuration class and enable the Swagger support. You can also use the @Bean annotation to create a Docket object that defines the API documentation and the Swagger UI settings.

To customize the Swagger UI, you need to create a SwaggerConfig class in your project and add the following code:

package com.example.spring.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.spring.swagger.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring MVC and Swagger Integration Demo")
                .description("This is a demo project for showing how to integrate Spring MVC and Swagger and customize the Swagger UI")
                .version("1.0.0")
                .build();
    }
}

This code creates a Docket object that specifies the base package of the controller classes, the path selectors, and the API information. The API information includes the title, the description, and the version of the API. You can change these values according to your preference.

After creating the SwaggerConfig class, you need to restart your application and refresh the Swagger UI. You will see the updated logo and title of the Swagger UI. You will also see the API information that you have provided. You can also modify the API information according to your needs.

In the next subsection, you will learn how to add custom CSS and JavaScript to the Swagger UI.

3.1. Changing the logo and title

In this subsection, you will learn how to change the logo and the title of the Swagger UI. You will use the apiInfo method in the SwaggerConfig class to specify the logo and the title of your API. You will also create a custom logo image and place it in the src/main/resources/static folder of your project.

The logo and the title of the Swagger UI are displayed at the top of the web page. They provide a visual identity and a brief introduction to your API. By default, the logo is the Swagger logo and the title is the name of your application. However, you can customize them to match your branding and your API description.

To change the logo and the title of the Swagger UI, you need to use the apiInfo method in the SwaggerConfig class. This method returns an ApiInfo object that contains the information and the settings of your API. You can use the ApiInfoBuilder class to create an ApiInfo object with the following attributes:

  • title: The title of your API.
  • description: The description of your API.
  • version: The version of your API.
  • termsOfServiceUrl: The URL of the terms of service of your API.
  • contact: The contact information of your API.
  • license: The license of your API.
  • licenseUrl: The URL of the license of your API.

You can use the title attribute to specify the title of your API. This title will be displayed as the title of the Swagger UI. You can also use the description attribute to specify the description of your API. This description will be displayed as the subtitle of the Swagger UI. You can also use the other attributes to provide more information and details about your API.

Here is an example of how to use the apiInfo method to change the logo and the title of the Swagger UI:

package com.example.spring.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.spring.swagger.controller"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring MVC and Swagger Integration Demo")

3.2. Adding custom CSS and JavaScript

In this subsection, you will learn how to add custom CSS and JavaScript to the Swagger UI. You will use the springfox-swagger-ui dependency and the src/main/resources/static folder of your project to include your own style and script files. You will also modify the index.html file of the Swagger UI to link to your custom files.

The CSS and JavaScript files of the Swagger UI are responsible for the appearance and the behavior of the web page. They define the layout, the colors, the fonts, the animations, and the interactions of the Swagger UI. By default, the Swagger UI uses the swagger-ui.css and swagger-ui-bundle.js files that are provided by the springfox-swagger-ui dependency. However, you can customize them by adding your own CSS and JavaScript files.

To add custom CSS and JavaScript files to the Swagger UI, you need to create a src/main/resources/static folder in your project and place your files there. This folder is the default location for serving static resources in Spring Boot applications. You can name your files as you wish, but make sure they have the .css and .js extensions. For example, you can create a custom.css and a custom.js file in the src/main/resources/static folder.

Then, you need to modify the index.html file of the Swagger UI to link to your custom files. The index.html file is the main HTML file that renders the Swagger UI. It is located in the springfox-swagger-ui.jar file that is downloaded by the springfox-swagger-ui dependency. You can extract this file and copy the index.html file to the src/main/resources/static folder of your project. This will override the default index.html file and allow you to customize it.

To link to your custom files, you need to open the index.html file in your IDE and locate the <head> section. Then, you need to add the following code snippets inside the <head> section:

<!-- Custom CSS -->
<link rel="stylesheet" type="text/css" href="custom.css" />

<!-- Custom JavaScript -->
<script src="custom.js"></script>

These code snippets link to your custom CSS and JavaScript files that are located in the same folder as the index.html file. You can also change the file names according to your preference, as long as they match the names of your files.

After adding these code snippets, you need to save the index.html file and restart your application. You will see the updated Swagger UI that reflects your custom CSS and JavaScript files. You can also modify the content of your files according to your needs.

In the next subsection, you will learn how to enable basic authentication for the Swagger UI.

4. Adding security to Swagger UI

In this section, you will learn how to add security to the Swagger UI and your API endpoints. You will use the spring-security dependency and the WebSecurityConfig class to enable basic authentication and secure your API with username and password. You will also configure the Swagger UI to prompt for the credentials and authorize the requests.

Security is an important aspect of any web application, especially when it exposes a RESTful API that can be accessed by anyone. By adding security to your API, you can prevent unauthorized access and protect your data and resources. By adding security to your Swagger UI, you can also restrict the access to your API documentation and testing interface.

To add security to your Swagger UI and your API endpoints, you need to use the spring-security dependency. This dependency provides the core functionality of Spring Security, such as authentication, authorization, and encryption. You can add this dependency to your pom.xml file and include the following code snippet:

<!-- Spring Security dependency -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

This code snippet specifies the groupId, artifactId, and version of the Spring Security dependency. You can also change the version according to your preference, as long as it is compatible with your Spring Boot version.

After adding this dependency, you need to create a WebSecurityConfig class in your project and configure the security settings. The WebSecurityConfig class is a Java class that you can create to configure the Spring Security features. You can use the @Configuration and @EnableWebSecurity annotations to mark this class as a Spring configuration class and enable the web security support. You can also extend the WebSecurityConfigurerAdapter class to customize the web security configuration.

To enable basic authentication and secure your API with username and password, you need to override the configure method of the WebSecurityConfigurerAdapter class and specify the authentication manager, the user details service, and the password encoder. You can also use the httpBasic method to enable the basic authentication and the antMatchers method to specify the URL patterns that require authentication. For example, you can use the following code to secure your API with the username user and the password password:

package com.example.spring.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected

4.1. Enabling basic authentication

In this section, you will learn how to enable basic authentication for your Swagger UI and your API endpoints. Basic authentication is a simple and widely used method of securing web resources. It requires the user to provide a username and password to access the resource. The username and password are encoded and sent in the HTTP header of the request.

To enable basic authentication for your Swagger UI and your API endpoints, you need to use Spring Security. Spring Security is a framework that provides comprehensive security features for Spring applications. It supports various authentication and authorization mechanisms, such as basic authentication, form-based authentication, OAuth2, JWT, etc.

To add Spring Security to your project, you need to modify the pom.xml file and include the following dependency:

<!-- Spring Security dependency -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

This dependency will enable the Spring Security support in your application. You can also specify the Spring Security version according to your preference.

To configure Spring Security in your application, you need to create a configuration class that extends the WebSecurityConfigurerAdapter class and overrides the configure methods. For example, you can use the following configuration class:

package com.example.spring.swagger.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // Define the users and roles for basic authentication
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("{noop}admin")
                .roles("ADMIN")
                .and()
                .withUser("user")
                .password("{noop}user")
                .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Enable basic authentication and disable CSRF protection
        http.httpBasic()
                .and()
                .csrf().disable();

        // Define the access rules for the API endpoints
        http.authorizeRequests()
                .antMatchers("/api/books/**").hasAnyRole("ADMIN", "USER")
                .antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**").permitAll()
                .anyRequest().authenticated();
    }
}

By using this configuration class, you can achieve the following:

  • Define two users (admin and user) and their roles (ADMIN and USER) for basic authentication. The passwords are prefixed with {noop} to indicate that they are plain text and no encoding is applied. You can also use other encoding methods, such as BCrypt or PBKDF2.
  • Enable basic authentication and disable CSRF protection for the application. CSRF protection is not needed for RESTful APIs, as they are stateless and do not use cookies or sessions.
  • Define the access rules for the API endpoints. The /api/books/** endpoints require either ADMIN or USER role, while the Swagger-related endpoints are accessible to anyone. Any other request requires authentication.

Now that you have enabled basic authentication for your Swagger UI and your API endpoints, you can run your application and access the Swagger UI at http://localhost:8080/swagger-ui/.

You can enter the username and password that you defined in the configuration class and access the Swagger UI. You can also test the API endpoints using the Swagger UI. You will see that the requests include the Authorization header with the encoded username and password.

In the next section, you will learn how to secure the API endpoints using Spring Security annotations.

4.2. Securing the API endpoints

In this section, you will learn how to secure the API endpoints using Spring Security annotations. Spring Security annotations are a convenient way of adding fine-grained access control to your API methods. You can use them to specify the roles or permissions required to access a specific method or class.

To use Spring Security annotations in your project, you need to enable the @EnableGlobalMethodSecurity annotation in your configuration class. This annotation allows you to use the following types of annotations:

  • @Secured: This annotation checks if the user has one of the specified roles to access the method.
  • @PreAuthorize: This annotation evaluates a SpEL expression before the method is executed to determine if the user can access the method.
  • @PostAuthorize: This annotation evaluates a SpEL expression after the method is executed to determine if the user can access the method.

Here is an example of how to enable the @EnableGlobalMethodSecurity annotation in your configuration class:

package com.example.spring.swagger.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
}

By using this configuration class, you can enable the @Secured and @PreAuthorize annotations in your project. You can also enable other types of annotations, such as @PostAuthorize or @RolesAllowed, by setting the corresponding attributes to true.

To use Spring Security annotations in your controller class, you need to annotate your methods or classes with the appropriate annotations. For example, you can use the following annotations:

package com.example.spring.swagger.controller;

import com.example.spring.swagger.model.Book;
import com.example.spring.swagger.service.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(“/api/books”)
@Api(value = “Book Controller”, description = “This controller manages the books in the system”)
public class BookController {

@Autowired
private

5. Conclusion

In this tutorial, you have learned how to integrate Swagger with Spring MVC to document and test your RESTful API. You have also learned how to customize the Swagger UI to change the logo and title, and how to add security to your Swagger UI and your API endpoints using basic authentication and Spring Security.

By following this tutorial, you have gained the following skills and knowledge:

  • How to set up Spring MVC and Swagger in your project using Maven and Spring Initializr.
  • How to configure Swagger annotations in your controller classes and methods to provide more information and details about your API.
  • How to customize the Swagger UI by changing the logo and title using a custom index.html file.
  • How to add custom CSS and JavaScript to the Swagger UI using a custom webjar.
  • How to enable basic authentication for your Swagger UI and your API endpoints using Spring Security.
  • How to secure the API endpoints using Spring Security annotations such as @Secured and @PreAuthorize.

You can find the complete source code of this tutorial on GitHub. You can also modify and extend the code to suit your needs and preferences.

We hope you enjoyed this tutorial and found it useful. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *