引入maven依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
添加配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContextList = new ArrayList<>();
List<SecurityReference> securityReferenceList = new ArrayList<>();
securityReferenceList.add(new SecurityReference("custom-token", scopes()));
securityContextList.add(SecurityContext
.builder()
.securityReferences(securityReferenceList)
.forPaths(PathSelectors.any())
.build()
);
return securityContextList;
}
private AuthorizationScope[] scopes() {
return new AuthorizationScope[]{new AuthorizationScope("global", "accessAnything")};
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeyList = new ArrayList<>();
apiKeyList.add(new ApiKey("custom-token", "custom-token", "header"));
return apiKeyList;
}
}
说明
此配置会在swagger-ui页面上部添加authorize模块,点击:
输入后就会在所有接口请求时在 header 中添加 custom-token:[value]
原文链接:https://blog.csdn.net/xuehuayouling/article/details/108232977