天天看點

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);
}      

繼續閱讀