我有一个Spring Boot应用程序,其中包含一些需要Bearer令牌的REST API。我正在使用Springfox自动生成REST API的标志。
我基于this answer定义了以下swagger配置类:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Autowired
private TypeResolver typeResolver;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
// .host("leonardo.cloud.reply.eu")
.useDefaultResponseMessages(false).select()
.apis(RequestHandlerSelectors.basePackage("it.reply.speech.analysis")).paths(PathSelectors.any())
.build().genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(newRule(
typeResolver.resolve(DeferredResult.class,
typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
typeResolver.resolve(WildcardType.class)))
.securitySchemes(Lists.newArrayList(apiKey())).apiInfo(apiInfo())
.securityContexts(Arrays.asList(securityContext()));
}
private ApiInfo apiInfo() {
return new ApiInfo("SpeechToText API", "API for Edison's SpeechToText data access", "0.1", "Terms of service",
new Contact("Blue Cognitive", "", ""), "No license", "", Collections.emptyList());
}
private ApiKey apiKey() {
return new ApiKey("apiKey", "Authorization", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.any()).build();
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference("apiKey", authorizationScopes));
}
}
现在在我敏捷的UI配置中,我有以下输出: 如果在 value 字段中添加 bearer bearer-token-value ,则该API可以正常工作。