全网唯一测试有效代码,不服来战!哈
package com.company.project;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors
.basePackage("com.company.project.web"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo())
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("springboot利用swagger构建api文档")
.description("简单优雅的restfun风格")
.termsOfServiceUrl("http://www.baidu.com").version("1.0")
.build();
}
// 通过Swagger2的securitySchemes配置全局参数:如下列代码所示,securitySchemes的ApiKey中增加个名为“Authorization”,type为“header”的参数。
private List <ApiKey> securitySchemes() {
List <ApiKey> keys = new ArrayList();
keys.add(new ApiKey("Authorization", "Authorization", "header"));
return keys;
}
在Swagger2的securityContexts中通过正则表达式,设置需要使用参数的接口 (或者说,是去除掉不需要使用参数的接口),如下列代码所示,通过PathSelectors.regex("^(?!auth).*$"),所有包含"auth"的接口不需要使用securitySchemes。即不需要使用上文中设置的名为“Authorization”,type为“header”的参数。
private List<SecurityContext> securityContexts() {
List <SecurityContext> securityContexts = new ArrayList();
securityContexts.add(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$")).build());
return securityContexts;
}
// 设置完成后进入SwaggerUI,右上角出现“Authorization”按钮,点击即可输入我们配置的参数。 对于不需要输入参数的接口(上文所述的包含auth的接口),在未输入Authorization参数就可以访问。 其他接口则将返回401错误。点击右上角“Authorization”按钮,输入配置的参数后即可访问。参数输入后全局有效,无需每个接口单独输入。
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(new SecurityReference("Authorization",authorizationScopes));
}
网友评论