Spring Cloud Gateway gateway integration Knife4j 4.3 implements microservice interface document aggregation

Author’s homepage: Youlai Technology
Open source projects: youlai-mall vue3-element-admin youlai-boot
Warehouse homepage: Gitee Github GitCode
Welcome to like Collect ?Leave a message Please correct any errors!

The opening picture

Article directory

  • A picture at the beginning
  • Preface
  • Spring Cloud integration Knife4j
    • pom.xml
    • application.yml
    • SwaggerConfig.java
    • Access single service interface documentation
  • Spring Cloud Gateway gateway aggregation
    • pom.xml
    • application.yml
    • Access the Gateway Aggregation Interface Documentation
  • Interface testing
    • Login authentication
    • Get user information
  • Conclusion
  • Source code

Foreword

The new version of youlai-mall open source microservice mall is based on Spring Boot 3 and Java 17, and also uses Knife4j 4.3. Different from the previous version, the new version of Knife4j no longer relies on the Springfox framework (which stopped updating in 2020) as the basic OpenAPI3 specification, but chose SpringDoc as the implementation of the OpenAPI3 specification of the underlying framework. Therefore, there are major differences in the new version compared to the previous version.

In the new version, you can refer to Knife4j official website for adaptation and upgrade. This article will introduce the integration of Knife4j 4.3 and microservices in the new version, Spring Cloud Gateway gateway aggregation, and how to automatically populate the access_token of the custom extended OAuth2 password mode of Spring Authorization Server.

Spring Cloud integration Knife4j

The Spring Cloud microservices here are other services besides the gateway (youlai-gateway), such as system services (youlai-system) and mall services (mall-*)

pom.xml

Add the maven dependency of knife4j, refer to Spring Boot 3 Integrating Knife4j

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
    <version>4.3.0</version>
</dependency>

application.yml

Except for packages-to-scan to scan the interface package path, other defaults can be used. Please refer to Spring Boot 3 Integration of Knife4j

spring:
  security:
    oauth2:
      authorizationserver:
      # OAuth2 authentication path
        token-uri: http://localhost:9999/youlai-auth/oauth2/token
        
# springdoc-openapi project configuration
springdoc:
  swagger-ui:
    path: /swagger-ui.html
    tags-sorter: alpha
    operations-sorter: alpha
  api-docs:
    path: /v3/api-docs
  group-configs:
    - group: 'default'
      paths-to-match: '/**'
      packages-to-scan:
      # Configure the interface document scanning package path. The path of each service is different. The following is the package path of the system service (youlai-system).
        - com.youlai.system.controller
      
# Enhanced configuration of knife4j, you don’t need to configure it if you don’t need to enhance it.
knife4j:
  enable: false
  setting:
    language: zh_cn

SwaggerConfig.java

package com.youlai.system.config;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.OAuthFlow;
import io.swagger.v3.oas.models.security.OAuthFlows;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;

/**
 * Swagger configuration class
 * <p>
 * Based on OpenAPI 3.0 specification + SpringDoc implementation + knife4j enhancement
 *
 * @author haoxr
 * @since 3.0.0
 */
@Configuration
public class SwaggerConfig {<!-- -->

    /**
     * OAuth2 authentication endpoint
     */
    @Value("${spring.security.oauth2.authorizationserver.token-uri}")
    private String tokenUrl;

    /**
     * OpenAPI configuration (metainformation, security protocol)
     */
    @Bean
    public OpenAPI apiInfo() {<!-- -->
        return new OpenAPI()
                .components(new Components()
                        .addSecuritySchemes(HttpHeaders.AUTHORIZATION,
                                newSecurityScheme()
                                        // OAuth2 authorization mode
                                        .type(SecurityScheme.Type.OAUTH2)
                                        .name(HttpHeaders.AUTHORIZATION)
                                        .flows(new OAuthFlows()
                                                .password(
                                                        newOAuthFlow()
                                                                .tokenUrl(tokenUrl)
                                                                .refreshUrl(tokenUrl)
                                                )
                                        )
                                        // Safe mode uses Bearer token (JWT)
                                        .in(SecurityScheme.In.HEADER)
                                        .scheme("Bearer")
                                        .bearerFormat("JWT")
                        )
                )
                //Add Authorization parameter globally to the interface
                .addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION))
                //Interface information definition
                .info(new Info()
                        .title("System Services")
                        .version("3.0.0")
                        .description("User, role, menu, department, dictionary and other interfaces")
                        .license(new License().name("Apache 2.0")
                                .url("https://www.apache.org/licenses/LICENSE-2.0"))
                );
    }


}

Access single service interface document

Visit Knife4j’s documentation address: http://ip:port/doc.html to view the documentation

The interface document address of the system service (youlai-system) is http://localhost:8800/doc.html. The access page is as follows:

Spring Cloud Gateway gateway aggregation

Refer to Knife4j official documentation: Spring Cloud Gateway gateway aggregation

Knife4j officially provides two aggregation methods: Manual configuration and Service discovery. If the number of microservices is small and there are customized document requirements, Manual configuration is recommended, otherwise Generally, the service discovery method is recommended, which can avoid the trouble of manually adding configuration every time a new service is added.

The service discovery aggregation method is used here. If you want to do it manually, please refer to the official configuration (very detailed)

pom.xml

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-gateway-spring-boot-starter</artifactId>
    <version>4.3.0</version>
</dependency>

application.yml

spring:
  cloud:
    gateway:
      discovery:
        locator:
          # Enable service discovery
          enabled: true
          lower-case-service-id: true
      #Gateway routing
      routes:
        - id: system service
          uri: lb://youlai-system
          predicates:
            - Path=/youlai-system/**
          filters:
            -StripPrefix=1

# knife4j gateway aggregation
knife4j:
  gateway:
    enabled: true
    #Specify the service discovery mode to aggregate microservice documents, and it is the default grouping
    strategy: discover
    discover:
      # OpenAPI 3.0 Specification
      version: openapi3
      enabled: true

Access gateway aggregation interface document

Visit Knife4j’s documentation address: http://ip:port/doc.html to view the documentation

The interface document address of the gateway (youlai-gateway) is http://localhost:9999/doc.html. The access page is as follows:

Interface testing

Next, do an OAuth2 login authentication (OAuth2 password mode extended by Spring Authorization Server). After successful authentication, you can get the access token (access_token) and request Get login user information interface test.

After the authentication is successful, if you open other interfaces, the request header will automatically carry the access token.

Login authentication

Click Authorize in the menu bar on the left side of the interface document to open the authentication page, fill in the OAuth2 password mode authorization authentication parameters as shown in the figure

Special reminder: Knife4j’s automatic filling of request headers requires the data to be returned natively. So what is the native data format?

  • Native data format

    {<!-- -->
        "access_token": "eyJraWQiOiJlNTg1NTQ3MS02ZDlmLTRkOWEtODJlNi1mN2QyNjY4YjhhZDgiLCJhbGciOiJSUzI1NiJ9.xxx.xxx",
        "refresh_token": "oYQz7UA4jafCfYZN7BW1cX6Kn-QGxNf1XIxKp-xxx",
        "token_type": "Bearer",
        "expires_in": 86400
    }
    
  • ?Packaging data format

    Custom data formats, such as those containing business codes, cannot be parsed by Knife4j, let alone automatically filled in.

    {<!-- -->
        "code": "00000",
        "data": {<!-- -->
            "access_token": "eyJraWQiOiJlNTg1NTQ3MS02ZDlmLTRkOWEtODJlNi1mN2QyNjY4YjhhZDgiLCJhbGciOiJSUzI1NiJ9.xxx.xxx",
            "refresh_token": "ImW57MWPEBQpcNpuPsX1l5eJCDtyoBMz-xxx",
            "token_type": "Bearer",
            "expires_in": 86400
        },
        "msg": "Everything is ok"
    }
    

client is a client ID reserved for the test interface in the code. For details, please see the processing of the MyAuthenticationSuccessHandler class

Get user information

After successful authentication, open the Get login user information interface and click on the request header to see that the access token has been automatically filled into the Authorization parameter of the request header.

Click Send and you can see that the data is returned successfully.

If you enter an incorrect access token, the message “Token is invalid or expired” is displayed, which is in line with the expected effect.

Conclusion

This article first introduces how to integrate Spring Cloud microservices with Knife4j 4.3, and uses the Spring Cloud Gateway to aggregate the interface documents of each service to achieve a more unified management method. Finally, we also explored how to test the Spring Authorization Server extension’s OAuth2 password mode authentication interface in the integrated interface document. Once authentication is successful, Knife4j automatically populates the access token, allowing you to easily access other interfaces.

At this point, the integration and debugging tutorial of the new version of youlai-mall interface documentation ends. I hope this article is helpful to you and can help you avoid various problems when using the new version.

Source code

Github Gitee
Open source Organization Youlai Open Source Organization Youlai Open Source Organization
Backend youlai-mall? ? youlai-mall
Front-end mall-admin mall-admin
Mobile terminal mall-app mall-app