swagger是一个很牛B的东东,但正常使用时,我们的接口需要登陆才能访问的。即登陆时,要传一个登陆后的token才能访问的。
那这个怎么设置,才可以让所有接口都允许登陆后访问呢。
解决办法如下:
@Configuration
@EnableWebMvc
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket platformApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).forCodeGeneration(true)
.select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.apis(RequestHandlerSelectors.any())
.paths(regex("^.*(?<!error)$"))
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeyList= new ArrayList();
apiKeyList.add(new ApiKey("x-auth-token", "x-auth-token", "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("starmark-API").description("©2018 Copyright. Powered By starmark.")
// .termsOfServiceUrl("")
.contact(new Contact("Starmark", "", "947618@163.com")).license("Apache License Version 2.0")
.licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE").version("2.0").build();
}
}
关键是在securitySchemes()方法配置里增加需要token的配置。
配置完成后,swagger-ui.html里右上角会有一个Authorize的按钮,录入该token即能成功调用相关接口
网友评论