<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
然后在启动springboot的启动类增加一个注解,@EnableOpenApi 就OK了。
不是swagger的问题,各种配置也都对,问题就在于,参数名!“Authorization” 这个header是用来存认证信息的,因为这次做的也正式认证接口,认证信息从这个header中获取。
结果正常的写法就无法获取这个header了。
swagger是有通用的或者叫做全局的添加认证信息的设置的,就比如你的接口都需要检查token就可以给所以的接口设置统一的token。
具体的开启如下:
@Bean
public Docket createRestApi() {
//返回文档摘要信息
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
//.globalRequestParameters(getGlobalRequestParameters());
//.globalResponses(HttpMethod.POST, getGlobalResonseMessage());
}
private List<SecurityScheme> securitySchemes() {
List<SecurityScheme> securitySchemes = new ArrayList<>();
securitySchemes.add(new ApiKey("Authorization", "Authorization", "header"));
return securitySchemes;
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$")).build());
return securityContexts;
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
return securityReferences;
}
同时还引出了另一个问题,如果要从header中获取这个参数,Authorization。不加注解,swagger也会自动给添加一个参数。参数名正是Authorization,不能用,但是不传还提示必填。