天天看点

SpringBoot JWT认证机制项目集成Swagger2

Swagger2 作为一个规范和完整的框架,可以用于生成、描述、调用和可视化 RESTful 风格的 Web 服务:

1、 接口文档在线自动生成,文档随接口变动实时更新,节省维护成本

2、 支持在线接口测试,不依赖第三方工具

该文将说明SpringBoot如何集成Swagger2,并通过Swagger配置类加入Header(token Authorization)参数,完成在线接口测试。

1、SpringBoot项目添加maven依赖

<!-- RESTful APIs swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-annotations</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.21</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
        </dependency>      

2、创建 Swagger2配置类

/**
 * Swagger2配置类
 *
 * @author zhuhuix
 * @date 2020-03-31
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    @SuppressWarnings("all")
    public Docket createRestApi() {
        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        ticketPar.name("Authorization").description("token")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .defaultValue("Bearer"+ " ")
                .required(true)
                .build();
        pars.add(ticketPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(true)
                .apiInfo(apiInfo())
                .select()
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build()
                .globalOperationParameters(pars);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("startup Api接口文档")
                .version("1.0")
                .build();
    }      

根据以下SpringFox的参数构造类中的定义,我们可以给Api增加Hearder类型参数,并标志为必要参数:

public class ParameterBuilder {

private static final Collection PARAMETER_TYPES_ALLOWING_EMPTY_VALUE = ImmutableList.of(“query”, “formData”);

private String name;

private String description;

private String defaultValue;

private boolean required;

private boolean allowMultiple;

private AllowableValues allowableValues;

private String paramType;

private String paramAccess;

private ResolvedType type;

private ModelReference modelRef;

}

效果如下:

SpringBoot JWT认证机制项目集成Swagger2

3、编写Controller Api接口

@Slf4j
@RestController
@RequestMapping("/api/security")
@Api(tags = "安全接口")
public class SecurityController {
    @ApiOperation(value = "接口测试",notes = "该接口仅用于测试")
    @PostMapping(value="/test")
    public Object test(){
        return "test";
    }
}      

4、登录Swagger UI测试

登录http://local:端口号/swagger-ui.html,界面显示如下

SpringBoot JWT认证机制项目集成Swagger2

打开测试接口输入参数,运行结果如下图

SpringBoot JWT认证机制项目集成Swagger2

5、分组设置

@Bean(value = "defaultApi")
public Docket defaultApi() {
    List<Parameter> pars = new ArrayList<Parameter>();

    ParameterBuilder tokenPar = new ParameterBuilder();
    tokenPar.name(headerToken).description(tokenDescription)
            .modelRef(new ModelRef("String")).parameterType("header")
            .required(tokenRequired).build(); //header中的Token参数必填,但是这里不能解决部分接口不需要token参数

    pars.add(tokenPar.build());
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(isEnable)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("project.api.auth"))
            .paths(PathSelectors.any())
            .build().groupName("需要token验证").globalOperationParameters(pars).ignoredParameterTypes(HttpServletResponse.class, HttpServletRequest.class);
}

@Bean(value = "publicApi")
public Docket publicApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(isEnable)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("project.api.pub"))
            .paths(PathSelectors.any())
            .build().groupName("无需token验证").ignoredParameterTypes(HttpServletResponse.class, HttpServletRequest.class);
}      

继续阅读