登陆

「swagger」 给API添加大局Header信息

admin 2020-02-14 135人围观 ,发现0个评论

关于swagger咱们都不生疏,团队前后端别离文档是必不可少的。在运用文档时,部分接口是需要在header中增加token等「swagger」 给API添加大局Header信息的认证信息,经过header参数是也能够,可是,每个接口都得写,作为程序猿,这个怎能忍受,一定要做个一了百了的装备,才契合咱们的气质。

装备

@Configuration
@EnableSwagger2
public class SwaggerConfig「swagger」 给API添加大局Header信息 {
@Value("${maven.project.version:null}")
private String projectVersion;
@Value("${maven.project.description:null}")
private String projectDescription;
@Value("${maven.build.time:null}")
private String projectBuildTime;
@Value("${spring.application.name:null}")
private String applicationName;
public SwaggerConfig() {
}
@Bean
public Docket createRestApi() {
return (new Docket(DocumentationType.SWAGGER_2)).apiInfo(this.apiInfo()).select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any()).build().securitySchemes(this.security()).securityContexts(this.securityContexts());
}
private ApiInfo apiInfo() {
return (new ApiInfoBuilder()).title(this.applicationName + " API文档").descri脾胃虚寒ption("BUILD TIME: " + this.projectBuildTime + "\n" + this.projectDescription).version(this.projectVersion).build();
}
private List security() {
return Arrays.asList(new ApiKey("JWT Token", "Authorization", "header"), new ApiKey("用户id", "user_id", "header"), new ApiKey("用户来历", "user_from", "header"));
}
private List securityContexts() {
List securityContexts = new ArrayList(1);
securityContexts.add(SecurityContext.builder().securityReferences(this.defaultAuth()).build());
return securityContexts;「swagger」 给API添加大局Header信息
}
List defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[]{authorizationScope};
List apiKeys = this.security();
List securityReferences = new ArrayList(apiKeys.size());
Iterator var5 = apiKeys.iterator();
while(var5.hasNext()) {
ApiKey item = (ApiKey)var5.next();
securityReferences.add(new SecurityReference(item.getName(), authorizationScopes));
}
return securityReferences;
}
}

对应的前端页面

请关注微信公众号
微信二维码
不容错过
Powered By Z-BlogPHP