我将swagger2集成到springboot项目中,因为我所有的端点授权都是通过OAuth2进行的,因此我需要向每个方法添加Authorization标头,例如以下代码:

@ApiImplicitParams({
    @ApiImplicitParam(paramType="header",name="Authorization",dataType="String",required=true, value="Bearer {access-token}")
})


这些相同的注释太多了,请问有什么方法可以重构它们?

Swagger2交易代码:

@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .ignoredParameterTypes(TokenInfo.class, HttpServletRequest.class, HttpServletResponse.class)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.xxx.yyy.resource"))
            .paths(PathSelectors.any())
            .build();
}

最佳答案

我花了几天时间找出解决方案。在这里,我为您提供了access_token的摘要配置。配置全局参数,可以说包含每个端点的通用参数(access_token)。因此,您不必在每个端点都包含@ApiImplicitParams。下面提供了可能的摘要配置(以后您可以更改自己的api信息)。

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.xxx.yyy.resource"))
            .paths(PathSelectors.any())
            .build()
            .globalOperationParameters(commonParameters())
            .apiInfo(apiInfo())
            .ignoredParameterTypes(TokenInfo.class, HttpServletRequest.class, HttpServletResponse.class)
            .securityContexts(Lists.newArrayList(securityContext()))
            .securitySchemes(Lists.newArrayList(apiKey()));
}


private List<Parameter> commonParameters() {
    List<Parameter> parameters = new ArrayList<Parameter>();
    parameters.add(new ParameterBuilder()
            .name("access_token")
            .description("token for authorization")
            .modelRef(new ModelRef("string"))
            .parameterType("query")
            .required(true)
            .build());

    return parameters;
}

private ApiInfo apiInfo() {
    ApiInfo apiInfo = new ApiInfo(
            "My REST API",
            "Some custom description of API.",
            "API TOS",
            "Terms of service",
            "[email protected]",
            "License of API",
            "API license URL");
    return apiInfo;
}

private SecurityContext securityContext() {
    return SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.any())
            .build();
}

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

private ApiKey apiKey() {
    return new ApiKey("AUTHORIZATION", "access_token", "header");
}


只需粘贴代码,然后从swagger-ui尝试,让我知道状态。

09-26 04:33