Skip to content

Commit

Permalink
swagger添加登陆认证
Browse files Browse the repository at this point in the history
  • Loading branch information
macrozheng committed Apr 13, 2019
1 parent 1bf9a4b commit cfa9871
Showing 1 changed file with 43 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,17 @@
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;

import java.util.ArrayList;
import java.util.List;

/**
* Swagger2API文档的配置
* Created by macro on 2018/4/26.
Expand All @@ -24,7 +31,9 @@ public Docket createRestApi(){
.select()
.apis(RequestHandlerSelectors.basePackage("com.macro.mall.controller"))
.paths(PathSelectors.any())
.build();
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}

private ApiInfo apiInfo() {
Expand All @@ -35,4 +44,37 @@ private ApiInfo apiInfo() {
.version("1.0")
.build();
}

private List<ApiKey> securitySchemes() {
//设置请求头信息
List<ApiKey> result = new ArrayList<>();
ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
result.add(apiKey);
return result;
}

private List<SecurityContext> securityContexts() {
//设置需要登录认证的路径
List<SecurityContext> result = new ArrayList<>();
result.add(getContextByPath("/brand/.*"));
result.add(getContextByPath("/product/.*"));
result.add(getContextByPath("/productCategory/.*"));
return result;
}

private SecurityContext getContextByPath(String pathRegex){
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex(pathRegex))
.build();
}

List<SecurityReference> defaultAuth() {
List<SecurityReference> result = new ArrayList<>();
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
result.add(new SecurityReference("Authorization", authorizationScopes));
return result;
}
}

0 comments on commit cfa9871

Please sign in to comment.