gpt4 book ai didi

java - Swagger2 太多相同的注释

转载 作者:行者123 更新时间:2023-12-02 02:27:15 24 4
gpt4 key购买 nike

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

@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 的文档配置。配置全局参数,可以说包含每个端点的公共(public)参数(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",
"myeaddress@company.com",
"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 尝试,然后让我知道状态。

关于java - Swagger2 太多相同的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47627469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com