Swagger access OAuth2 authentication

1.pom dependency

Reference the Swagger dependency in the project where you want to use Swagger

<dependencies>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
</dependencies>

2.Swagger configuration class

The configuration class is marked with @ EnableSwagger2, which indicates that the Swagger function is enabled

package cc.mrbird.febs.server.system.configure;

import cc.mrbird.febs.server.system.properties.FebsServerSystemProperties;
import cc.mrbird.febs.server.system.properties.FebsSwaggerProperties;
import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.OAuthBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.GrantType;
import springfox.documentation.service.ResourceOwnerPasswordCredentialsGrant;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @description:
 * @Author ztt
 * @create: 2021-10-24 15:09
 */
@Configuration
@EnableSwagger2
public class FebsWebConfigure {
    
    @Autowired
    private FebsServerSystemProperties properties;
    
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        List<ISqlParser> sqlParserList = new ArrayList<>();
        sqlParserList.add(new BlockAttackSqlParser());
        paginationInterceptor.setSqlParserList(sqlParserList);
        return paginationInterceptor;
    }
    /**
     * This is the main method, and other methods are taken out
     * Write the controller path of the document to be generated in the basePackage
     */
    @Bean
    public Docket swaggerApi() {
        FebsSwaggerProperties swagger = properties.getSwagger();
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage(swagger.getBasePackage()))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo(swagger))
    }
    /**
     * This method is mainly to write some document descriptions
     */
    private ApiInfo apiInfo(FebsSwaggerProperties swagger) {
        return new ApiInfo(
                swagger.getTitle(),
                swagger.getDescription(),
                swagger.getVersion(),
                null,
                new Contact(swagger.getAuthor(), swagger.getUrl(), swagger.getEmail()),
                swagger.getLicense(), swagger.getLicenseUrl(), Collections.emptyList());
    }
}

APIs (requesthandlerselectors. Basepackage) of swaggerApi method (swagger. Getbasepackage())

))Means that all controllers under the cc.mrbird.febs.server.system.controller path are added, and paths(PathSelectors.any()) means that all methods in the Controller are included.

apiInfo is used to define some API page information, such as author name, email, website link, open source protocol, etc.

There are many fixed configurations here (called "magic value" in Ali programming specification). We can extract it into a configuration file. Create a new properties package under the cc.mrbird.febs.server.system path of the FEBS system module, and then create a new febswaggerproperties configuration file class under the package:

@Data
public class FebsSwaggerProperties{
    
    private String basePackage;
    private String title;
    private String description;
    private String version;
    private String author;
    private String url;
    private String email;
    private String license;
    private String licenseUrl;
    
    private String grantUrl;
    private String name;
    private String scope;
    
}
@Data
@SpringBootConfiguration
@PropertySource(value = {"classpath:febs-server-system.properties"})
@ConfigurationProperties(prefix = "febs.server.system")
public class FebsServerSystemProperties {
    /**
     * Authentication free URI. Multiple values are separated by commas
     */
    private String anonUrl;
    
    private FebsSwaggerProperties swagger = new FebsSwaggerProperties();
}

Then add swagger related resource configuration in the authentication free path of the febs-server-system.properties configuration file:

Restart the FEBS server system module to access   http://localhost:8301/system/swagger-ui.html

 

3. Certification oauth2

Although we have successfully accessed Swagger, because our resources are protected by the resource server, Swagger cannot perform normal interface testing. Therefore, authentication of oauth2 should be carried out

catalogue

1.pom dependency

2.Swagger configuration class

3. Certification oauth2

Configure a new Client in the FEBS auth module for Swagger token issuance. Add the following configuration in the febs-auth.properties configuration file of the FEBS auth module:

febs.auth.clients[1].client=swagger
febs.auth.clients[1].secret=123456
febs.auth.clients[1].grantType=password
febs.auth.clients[1].scope=test

  Modify Swagger's configuration class

package cc.mrbird.febs.server.system.configure;

import cc.mrbird.febs.server.system.properties.FebsServerSystemProperties;
import cc.mrbird.febs.server.system.properties.FebsSwaggerProperties;
import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.OAuthBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.GrantType;
import springfox.documentation.service.ResourceOwnerPasswordCredentialsGrant;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @description:
 * @Author ztt
 * @create: 2021-10-24 15:09
 */
@Configuration
@EnableSwagger2
public class FebsWebConfigure {
    
    @Autowired
    private FebsServerSystemProperties properties;
    
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        List<ISqlParser> sqlParserList = new ArrayList<>();
        sqlParserList.add(new BlockAttackSqlParser());
        paginationInterceptor.setSqlParserList(sqlParserList);
        return paginationInterceptor;
    }
    /**
     * This is the main method, and other methods are taken out
     * Write the controller path of the document to be generated in the basePackage
     */
    @Bean
    public Docket swaggerApi() {
        FebsSwaggerProperties swagger = properties.getSwagger();
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage(swagger.getBasePackage()))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo(swagger))
                .securitySchemes(Collections.singletonList(securityScheme(swagger)))
                .securityContexts(Collections.singletonList(securityContext(swagger)));
    }
    /**
     * This method is mainly to write some document descriptions
     */
    private ApiInfo apiInfo(FebsSwaggerProperties swagger) {
        return new ApiInfo(
                swagger.getTitle(),
                swagger.getDescription(),
                swagger.getVersion(),
                null,
                new Contact(swagger.getAuthor(), swagger.getUrl(), swagger.getEmail()),
                swagger.getLicense(), swagger.getLicenseUrl(), Collections.emptyList());
    }
    /**
     * It is used to configure security policies, such as authentication model, scope, etc
     */
    private SecurityScheme securityScheme(FebsSwaggerProperties swagger) {
        GrantType grantType = new ResourceOwnerPasswordCredentialsGrant(swagger.getGrantUrl());
        
        return new OAuthBuilder()
                .name(swagger.getName())
                .grantTypes(Collections.singletonList(grantType))
                .scopes(Arrays.asList(scopes(swagger)))
                .build();
    }
    /**
     * The security context for swagger2 authentication is set here
     */
    private SecurityContext securityContext(FebsSwaggerProperties swagger) {
        return SecurityContext.builder()
                .securityReferences(Collections.singletonList(new SecurityReference(swagger.getName(), scopes(swagger))))
                .forPaths(PathSelectors.any())
                .build();
    }
    /**
     * Here is the scope that allows authentication
     */
    private AuthorizationScope[] scopes(FebsSwaggerProperties swagger) {
        return new AuthorizationScope[]{
                new AuthorizationScope(swagger.getScope(), "")
        };
    }
}

  The security policy and security context are set through the securitySchemes and securityContexts methods of Docket.

In the securityScheme method, we built the security policy through the OAuthBuilder object, mainly configured the authentication type as ResourceOwnerPasswordCredentialsGrant (i.e. password mode), and the authentication address is http://localhost:8301/auth/oauth/token (that is, forward to the authentication server through the gateway). The scope is test, which is consistent with the definition in the FEBS auth module. This security policy is named febs_oauth_swagger.

In the securityContext method, we use FEBS_ oauth_ The swagger name is associated with the security policy defined above, and this security context is set for all API interfaces through forPaths(PathSelectors.any()).

Restart the service and re access the Swagger service:

  There will be an authentication button, click to authenticate

  After successful authentication, the interface test can be carried out normally.

Keywords: Java Nginx data structure list

Added by mrwowza on Mon, 22 Nov 2021 16:44:32 +0200