SoFunction
Updated on 2025-04-06

A brief analysis of how to use Swagger to generate API documentation with permission control

In our development work, API documents are like project instructions. Clear and accurate documents can greatly improve our development efficiency. And when it comes to permission control, how to generate both secure and detailed API documents becomes a key issue. Today, I will talk to you about how to use Swagger to generate API documents with permission control.

Preparation

When we do development, it is like marching and fighting, tools and resources are our "food and grass". Before using Swagger to generate API documentation with permission control, you must add relevant dependencies to the project. If you are using the Maven project, add the following dependencies:

<dependencies>
    <!-- Swagger API annotation -->
    <dependency>
        <groupId></groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <!-- Swagger UI -->
    <dependency>
        <groupId></groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
    <!-- Spring Security -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
</dependencies>

These dependencies are like our weapons and equipment. With them, we can "break through obstacles" on the battlefield of development.

Configure Swagger

With dependencies, Swagger is configured so that it can generate API documents according to our needs. Creating a Swagger configuration class is like setting up a stage for a performance:

import ;
import ;
import ;
import ;
import ;
import ;
import ..EnableSwagger2;
 
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
               .select()
               .apis((""))
               .paths(())
               .build();
    }
}

Here we specify the path of the controller package to scan so that Swagger can know where to get the API information.

Permission control

In actual projects, API documents often contain a lot of sensitive information, so it is very necessary to add permission control to the documents. We use Spring Security to implement this function and create a Spring Security configuration class:

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
@Configuration
@EnableWebSecurity
public class SecurityConfig {
 
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
               .authorizeRequests()
               .antMatchers("/", "/swagger-resources/**", "/v2/api-docs").hasRole("ADMIN")
               .anyRequest().authenticated()
               .and()
               .httpBasic();
        return ();
    }
 
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user =
             ()
               .username("admin")
               .password("password")
               .roles("ADMIN")
               .build();
 
        return new InMemoryUserDetailsManager(user);
    }
}

In this configuration, we stipulate that only users with the ADMIN role can access the paths related to Swagger UI and API documents, just like adding a security lock to the document, which can only be opened by people with keys.

Add permission annotations to the API

In the controller method, we need to add permission annotations and Swagger annotations, so that we can clearly see the permission requirements of each API in the generated document:

import ;
import ;
import ;
import ;
import ;
import ;
 
@RestController
@RequestMapping("/api")
@Api(value = "Sample API", description = "This is an example API documentation with permission control")
public class ExampleController {
 
    @GetMapping("/hello")
    @ApiOperation(value = "Get Greetings", notes = "Requires an ADMIN role to access")
    @PreAuthorize("hasRole('ADMIN')")
    public String hello() {
        return "Hello, World!";
    }
}

Here we use the @PreAuthorize annotation to control the method's permissions, and at the same time, the permission requirements are explained in the notes attribute of the @ApiOperation annotation, just like posting a "user instructions" to each API.

View the document

When we complete all the above steps, we can start the Spring Boot application and visit http://localhost:8080/ (the port number is modified according to the actual situation). At this time, the browser will pop up the HTTP Basic Authentication dialog box, enter the user name and password we configured in SecurityConfig (here is admin and password). After the authentication is passed, you can see the API document with permission information, which is like opening a door to a treasure house of knowledge.

Things to note

In actual projects, we need to pay attention to some details. For example, the withDefaultPasswordEncoder() used in the example is not very safe, and it is recommended to use more secure password storage methods such as BCryptPasswordEncoder. In addition, we can adjust permission rules and authentication methods according to actual business needs, such as using OAuth2, etc.

This is the article about how to use Swagger to generate API documents with permission control. For more relevant contents of Swagger to generate API documents, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!