Spring Boot 尝试添加swagger配置以随请求发送授权标头后,应用程序无法启动

rekjcdws  于 2022-11-23  发布在  Spring
关注(0)|答案(4)|浏览(139)

我尝试添加一个swagger config类,允许我发送一个带有swagger请求的承载令牌,然后在本地运行我的API时,我遇到了一个错误。我已经尝试了所有我能找到的在google上看起来相关的东西,但没有成功。我是一个相当新的swagger,所以任何指针都非常感谢。这是我的config类的样子:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.documentation.builders.PathSelectors;
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 javax.servlet.ServletContext;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Configuration
@EnableSwagger2
@Import(springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig {

    @Bean
    public Docket api(ServletContext servletContext) {
        return new Docket(DocumentationType.SWAGGER_2)
               .securitySchemes(Arrays.asList(apiKey()))
                .securityContexts(Collections.singletonList(securityContext()));
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("/.*")).build();
    }

    private List<SecurityReference> defaultAuth() {
        final AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        final AuthorizationScope[] authorizationScopes = new AuthorizationScope[]{authorizationScope};
        return Collections.singletonList(new SecurityReference("Bearer", authorizationScopes));
    }

    private ApiKey apiKey() {
        return new ApiKey("Bearer", "Authorization", "header");
    }
}

我得到的错误如下:

2020-05-19 17:37:38,437 | WARN  | org.springframework.context.support.AbstractApplicationContext:558 - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'apiModelPropertyPropertyBuilder' defined in URL [jar:file:/C:/Users/jbrooks58/.m2/repository/io/springfox/springfox-swagger-common/2.9.2/springfox-swagger-common-2.9.2.jar!/springfox/documentation/swagger/schema/ApiModelPropertyPropertyBuilder.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'springfox.documentation.spring.web.DescriptionResolver' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in springfox.documentation.swagger.schema.ApiModelPropertyPropertyBuilder required a bean of type 'springfox.documentation.spring.web.DescriptionResolver' that could not be found.

Action:

Consider defining a bean of type 'springfox.documentation.spring.web.DescriptionResolver' in your configuration.

谢谢你们的帮助!

hs1ihplo

hs1ihplo1#

我假设您在这里使用的是OAuth2。
你能不能试试

private ApiKey apiKey() {
        return new ApiKey("JWT", "Authorization", "header");
    }

及移去了

.securityContexts(Collections.singletonList(securityContext()))

你会得到这样的东西在你的 swagger

rxztt3cl

rxztt3cl2#

这对我来说是可行的,但是你必须把令牌与Bearer <token>前缀放在一起,没有前缀就不能使它工作。

@Configuration
@EnableSwagger2
public class ApiDocsConfig {

    @Value("${spring.application.name:N/A}")
    private String applicationName;

    @Value("${wind.version:N/A}")
    private String version;

    @Value("${wind.description:N/A}")
    private String description;

    @Value("${wind.developer:N/A}")
    private String developer;

    @Bean
    public Docket apiDocket() {
        HashSet<String> contentType = new HashSet<>();
        contentType.add("application/json");
        return new Docket(DocumentationType.SWAGGER_2)
                .produces(contentType) //Or whatever default value(s)
                .consumes(contentType)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(metadata())
                .securitySchemes(Collections.singletonList(new ApiKey("JWT", "Authorization", "header")))
                .securityContexts(
                        Collections.singletonList(
                                SecurityContext.builder().securityReferences(
                                        Collections.singletonList(SecurityReference.builder().reference("JWT").scopes(new AuthorizationScope[0]).build())
                                ).build()
                        )
                );
    }

    private ApiInfo metadata() {
        return new ApiInfoBuilder()
                .title(this.applicationName)
                .description(this.description)
                .version(this.version)
                .contact(new Contact(null, null, this.developer))
                .build();
    }
}
nimxete2

nimxete23#

我和你遇到了同样的问题。我发现这个问题是由于pom.xml配置造成的。

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

当您尝试混合版本3.0.0和2.9.2时会出现问题,因此在我的情况下,我只需将3.0.0更改为2.9.2,问题就解决了。

cnwbcb6i

cnwbcb6i4#

面对类似的问题,更改依赖项版本对我的Gradle依赖项有效:

implementation "io.springfox:springfox-boot-starter:3.0.0"

我正在使用的SpringBoot版本:2.1.13.
您还可以通过将config类创建为

@Configuration 
@EnableSwagger2
public class SpringFoxConfig {
    @Bean
    public Docket apiDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

您可以访问您的swagger端点

http://host-name/servlet-context/v2/api-docs
http://host-name/servlet-context/swagger-ui/index.html

相关问题