swagger添加全局token
swagger 目前来说还是是一个很完善的接口文档说明和测试接口的工具,但正常使用时,我们的接口需要登陆才能访问的。
即登陆时,要传一个登陆后的token才能访问的。
那这个怎么设置,才可以让所有接口都允许登陆后访问呢。
解决办法如下:
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
ParameterBuilder ticketPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
ticketPar.name("Authorization").description("token")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build();
pars.add(ticketPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.****.cloud.wsdl.controller"))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
// .globalOperationParameters(pars)
;
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeyList= new ArrayList();
apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
return apiKeyList;
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts=new ArrayList<>();
securityContexts.add(
SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build());
return securityContexts;
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences=new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
return securityReferences;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("cloud-demo 业务相关APIs")
.description("cloud-demo 业务相关APIs")
.termsOfServiceUrl("http://apiDocs.cloud.com")
.version("1.0")
.build();
}
}
关键是在securitySchemes()方法配置里增加需要token的配置。
配置完成后,swagger-ui.html里右上角会有一个Authorize的按钮,录入该token即能成功调用相关接口