swagger2UI之swagger-bootstrap-ui的Authorize 功能

用Swagger测试接口的时候请求头需要携带token参数,swagger-bootstrap-ui就为我们提供了这样的功能。
需要注意的是,swagger-bootstrap-ui在1.9.6版本后更名为knife4j,起始版本仍然为1.9.6,推荐使用最新版。
1、背景
(1)Spring Cloud项目
(2)依赖版本

2.9.2
1.9.6
1.9.6
2.9.2

具体依赖:
a.网关处pom添加的依赖:


    com.github.xiaoymin
    knife4j-spring-boot-starter
    ${knife4j.version}

b.工程pom添加的依赖:



    io.springfox
    springfox-swagger2
    2.9.2


    io.springfox
    springfox-swagger-ui
    2.9.2


    com.github.xiaoymin
    swagger-bootstrap-ui
    1.9.6


    com.github.xiaoymin
    knife4j-micro-spring-boot-starter
    1.9.6


    io.springfox
    springfox-bean-validators
    2.9.2

两处依赖请注意knife4j的不同。
2、在工程项目web包下 XxxWebApplication的同级添加SwaggerConfiguration配置类。
参考的是 knife4j官方文档官方demo
我的仅供参考:

package com.cetc.xxx;

import com.fasterxml.classmate.TypeResolver;
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.github.xiaoymin.swaggerbootstrapui.model.OrderExtensions;
import com.github.xiaoymin.swaggerbootstrapui.service.SpringAddtionalModelService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
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.List;

@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfiguration {

    @Autowired
    SpringAddtionalModelService springAddtionalModelService;

    private final TypeResolver typeResolver;

    @Autowired
    public SwaggerConfiguration(TypeResolver typeResolver) {
        this.typeResolver = typeResolver;
    }

    @Bean(value = "defaultApi")
    @Order(value = 1)
    public Docket defaultApi() {
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        List parameters = Lists.newArrayList();
        parameterBuilder
                .name("token")
                .description("token令牌")
                .modelRef(new ModelRef("String"))
                .parameterType("header")
                .defaultValue("Bearer")
                .required(false).build();
        parameters.add(parameterBuilder.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("默认接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("xxx"))
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .extensions(Lists.newArrayList(new OrderExtensions(1)))
                .globalOperationParameters(parameters)
                .securityContexts(Lists.newArrayList(securityContext()))
                .securitySchemes(Lists.newArrayList(apiKey()));
    }

    private ApiKey apiKey() {
        return new ApiKey("BearerToken", "Authorization", "header");
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("/.*"))
                .build();
    }

    List defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Lists.newArrayList(new SecurityReference("BearerToken", authorizationScopes));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("xxxRESTful APIs")
                .description("Swagger2 RESTful APIs")
                .contact(new Contact("xxx公司", "", ""))
                .termsOfServiceUrl("http://{ip}:{port}/xxx/doc.html")
                .version("1.0")
                .build();
    }

    /**
     * ----------------------------- 各web的Controller层接口 -----------------------------
     **/

    @Bean(value = "xxApi")
    public Docket xxApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("xx接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cetc.spiderMan.xx.web"))
                .paths(PathSelectors.any())
                .build()
//                .additionalModels(typeResolver.resolve(DeveloperApiInfo.class))//name、email、role实体类
                .extensions(Lists.newArrayList(new OrderExtensions(2)))
                .securityContexts(Lists.newArrayList(securityContext(), securityContext1()))
                .securitySchemes(Lists.newArrayList(apiKey1(), apiKey()))
                ;
    }

    @Bean(value = "xxxApi")
    public Docket xxxApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("xxx接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cetc.spiderMan.xxx.web"))
                .paths(PathSelectors.any())
                .build()
                .extensions(Lists.newArrayList(new OrderExtensions(2)))
                .securityContexts(Lists.newArrayList(securityContext(), securityContext1()))
                .securitySchemes(Lists.newArrayList(apiKey1(), apiKey()))
                ;

    }

    @Bean(value = "xxxxApi")
    public Docket xxxxApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("xxxx接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cetc.spiderMan.xxxx.web"))
                .paths(PathSelectors.any())
                .build()
                .extensions(Lists.newArrayList(new OrderExtensions(2)))
                .securityContexts(Lists.newArrayList(securityContext(), securityContext1()))
                .securitySchemes(Lists.newArrayList(apiKey1(), apiKey()))
                ;
    }

    private ApiKey apiKey1() {
        return new ApiKey("BearerToken1", "Authorization-x", "header");
    }

    private SecurityContext securityContext1() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth1())
                .forPaths(PathSelectors.regex("/.*"))
                .build();
    }

    List defaultAuth1() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Lists.newArrayList(new SecurityReference("BearerToken1", authorizationScopes));
    }
}

3、WebApplication加注解:
例如:

@SpringBootApplication
@EnableSwagger2
@EnableSwaggerBootstrapUI
@EnableFeignClients("com.xxx")
public class XxxWebApplication {

    public static void main(String[] args) {
        SpringApplication.run(XxxWebApplication.class, args);
    }

}

接下来还要在Controller层以及相应的实体类添加注解,
Controller层添加注解方法参考我的这篇文章:https://blog.csdn.net/u010250240/article/details/101939606
4、项目启动后,访问其doc.html链接
就有了Authorize:
在这里插入图片描述
官方demo效果:http://swagger-bootstrap-ui.xiaominfo.com/doc.html

如有问题欢迎交流探讨~

你可能感兴趣的:(Java)