欢迎加入站点基地设计开发交流群:30720409
详细内容
当前位置 首页 >> 技术文档 >> Java >> 正文
Swagger2添加Authorization请求Token
发布日期:2021-11-04     点击:341     字体:[ ]


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;

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

/**
* Swagger配置
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
   public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
.apiInfo(apiInfo());
   }

private List securitySchemes() {
List apiKeys = new ArrayList<>();
       apiKeys.add(new ApiKey("Authorization", "Authorization", "header"));
       return apiKeys;
   }

private List securityContexts() {
List securityContexts = new ArrayList<>();
       securityContexts.add(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$")).build());
       return securityContexts;
   }

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

private ApiInfo apiInfo() {
return new ApiInfoBuilder().build();
   }
}

这样生成的swagger2接口文档就有一个要输入token的Authorize按钮,注意,输入的token前面可能需要加上Bearer ,再加上token才验证通过,Bearer后面有个空格。

用户评论
昵称 
内容  *
验证码   
   
Copyright © 2010 zdbase.com All Rights Reserved. 苏ICP备15039389号-1 可人软件设计