阅读量:0
1.导入swagger依赖
这里使用的是springfox-boot-starter,同时导入knife4j插件(不导入也行,导入可以方便接口调试)。
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency>
接下来编写swagger配置类
@Configuration @EnableOpenApi @EnableKnife4j public class Knife4jConfig { @Bean public Docket defaultApi2() { return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) //分组名称 // .groupName("2.X版本") .select() //这里指定Controller扫描包路径 .apis(RequestHandlerSelectors.basePackage("")) .paths(PathSelectors.any()) .build() .securitySchemes(securitySchemes()) .securityContexts(securityContexts()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("项目名称") .version("1.0") .build(); } private List<SecurityScheme> securitySchemes() { List<SecurityScheme> securitySchemeList = new ArrayList<>(); securitySchemeList.add(new HttpAuthenticationScheme("Authorization", "JWT授权(数据将在请求头中进行传递)直接在下面框中输入token", "http", "Bearer", "JWT", new ArrayList<>() )); return securitySchemeList; } //过滤不需要进行验证的页面 private List<SecurityContext> securityContexts() { List<SecurityContext> securityContexts = new ArrayList<>(); securityContexts.add( SecurityContext.builder() .securityReferences(defaultAuth()) //这些接口不用提供token即可访问。 .forPaths(PathSelectors.regex("^(?!/employee/login).*$")) .forPaths(PathSelectors.regex("^(?!/identifyImageBase64).*$")) .build()); return securityContexts; } //全局的token配置 private List<SecurityReference> defaultAuth() { List<SecurityReference> securityReferences = new ArrayList<>(); securityReferences.add(new SecurityReference("Authorization", new AuthorizationScope[0])); return securityReferences; } }
在swagger文档中效果如下
在/swagger-ui/index.html#/中可以全局配置token,并自动过滤不需要token的接口
在knife4j文档中也可以实现配置全局token
结束。