【问题标题】:Springfox swagger-ui.html unable to infer base URL - Caused by missing cookiesSpringfox swagger-ui.html 无法推断基本 URL - 由缺少 cookie 引起
【发布时间】:2018-08-15 18:17:30
【问题描述】:

我们的 Spring Boot 服务位于 API 网关后面。使用 Springfox 的早期版本 - 2.1.2,我们在加载 swagger-ui.html 页面时没有问题。这适用于 Spring Boot 1.4.3.RELEASE。从那时起,我们已经升级到 Boot 1.5.7,并将 Springfox 升级到 2.8.0。

现在,如果我们加载页面,我们会看到一个带有以下长消息的警告框。

无法推断基本网址。这在使用动态 servlet 时很常见 注册或当 API 位于 API 网关后面时。基本网址是 提供所有 swagger 资源的根。例如如果 该 API 可在http://example.org/api/v2/api-docs 获得,然后 基本网址是http://example.org/api/。请输入位置 手动

我在网上搜索了一些提示,但这些情况似乎不适用于我们。一方面,如果我只是简单地恢复版本,它就会通过同一个 API 网关重新开始工作。

跟踪流量,.html 页面对三个 XHR 资源的调用似乎引起了问题。这些从我们的 API 网关返回 401。他们返回 401 的原因是因为 cookie 没有传递。

三个调用分别是:

如果我将这些 URL 作为纯浏览器请求加载 - 它们可以工作 - 因为发送了 cookie。

我怀疑 CORS 是否适用,因为 HTML 是从与 swagger JSON 和实际服务调用相同的地址提供的。

知道为什么会发生这种情况吗?有人遇到过类似的问题吗?解决方法的建议?非常感谢。

【问题讨论】:

    标签: spring spring-boot swagger swagger-ui springfox


    【解决方案1】:

    添加安全配置 -- 以下 URLS 被跳过以进行身份​​验证 ::

    private static final String[] AUTH_WHITELIST = {
            "/swagger-resources/**",
            "/swagger-ui.html",
            "/v2/api-docs",
            "/webjars/**"
    };
    
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(AUTH_WHITELIST);
    }
    

    【讨论】:

      【解决方案2】:

      在 Spring Boot 类中添加以下注释为我解决了这个问题。

      @EnableSwagger2

      我用的是swagger版本

       <version>2.9.2</version>
      

      【讨论】:

        【解决方案3】:

        请参阅下面的编辑

        你使用弹簧安全吗?

        如果是,您可能会跳过一些这样的资源(对吗?): "/swagger-resources/**", "/swagger-ui.html", "/v2/api-docs", "/webjars/**"

        尝试将 "/swagger-resources/**" 更改为 "**/swagger-resources/**"

        我对 swagger 的具体安全配置是:

        private static final String[] AUTH_LIST = {
                // -- swagger ui
                "**/swagger-resources/**",
                "/swagger-ui.html",
                "/v2/api-docs",
                "/webjars/**"
        };
        
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .authorizeRequests().antMatchers(AUTH_LIST).authenticated()
            .and()
            .httpBasic().authenticationEntryPoint(swaggerAuthenticationEntryPoint())
            .and()
            .csrf().disable();
        }
        
        @Bean
        public BasicAuthenticationEntryPoint swaggerAuthenticationEntryPoint() {
            BasicAuthenticationEntryPoint entryPoint = new BasicAuthenticationEntryPoint();
            entryPoint.setRealmName("Swagger Realm");
            return entryPoint;
        }
        

        如果您需要/想要,我可以将示例项目发送到 GitHub,让您了解有关我的安全/swagger 配置的更多信息。

        编辑 2018/04/10

        这个问题是springfox版本错误造成的。 See this issue on github to solve the problem.

        给后代:

        在 pom.xml 中

        ...
        <repositories>
            <repository>
                <id>swagger</id>
                <name>swagger</name>
                <url>http://oss.jfrog.org/artifactory/oss-snapshot-local</url>
            </repository>
        </repositories>
        ...
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.1-SNAPSHOT</version>
        </dependency>
        ...
        

        扩展 WebSecurityConfigAdapter 的类:

        @Configuration
        public class WebSecurityConfigEntryPointApplication extends WebSecurityConfigurerAdapter {
        
            private static final List<String> AUTH_LIST = Arrays.asList(
                    "/swagger-resources/**",
                    "/swagger-ui.html**",
                    "/webjars/**",
                    "favicon.ico");
        
            @Autowired
            private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
        
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http
                        .antMatcher("/**").authorizeRequests().anyRequest().authenticated()
                        .and()
                        .exceptionHandling()
                        .defaultAuthenticationEntryPointFor(swaggerAuthenticationEntryPoint(), new CustomRequestMatcher(AUTH_LIST))
                        .and()
                        .httpBasic()
                        .authenticationEntryPoint(restAuthenticationEntryPoint)
                        .and()
                        .csrf().disable();
            }
        
            @Bean
            public BasicAuthenticationEntryPoint swaggerAuthenticationEntryPoint() {
                BasicAuthenticationEntryPoint entryPoint = new BasicAuthenticationEntryPoint();
                entryPoint.setRealmName("Swagger Realm");
                return entryPoint;
            }
        
            private class CustomRequestMatcher implements RequestMatcher {
        
                private List<AntPathRequestMatcher> matchers;
        
                private CustomRequestMatcher(List<String> matchers) {
                    this.matchers = matchers.stream().map(AntPathRequestMatcher::new).collect(Collectors.toList());
                }
        
                @Override
                public boolean matches(HttpServletRequest request) {
                    return matchers.stream().anyMatch(a -> a.matches(request));
                }
        
            }
        
        }
        

        RestAuthenticationEntryPoint:

        @Component
        public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
        
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            }
        }
        

        【讨论】:

        【解决方案4】:

        这发生在我身上,我使用的是 SpringBoot 1.5.16 和 Springfox 2.9.1。

        在我的application.properties 中,我定义了server.servlet-path=/api,但不知何故,swagger-ui 忽略了定义的值。我尝试了很多不同的方法来完成这项工作,最后我找到了解决方法:

         @Configuration
         @EnableSwagger2
         public class SwaggerConfiguration extends WebMvcConfigurationSupport {                                    
        
            @Bean
            public Docket apiMonitoramento() { 
                return new Docket(DocumentationType.SWAGGER_2)
                        .select()                                  
                        .apis(RequestHandlerSelectors.any())
                        .paths(PathSelectors.any())                          
                        .build()    
                        .apiInfo(apiInfo());
            }
        
            private ApiInfo apiInfo() {
                return new ApiInfoBuilder()              
                        .title("REST API")
                        .description("Servicesx")               
                        .build();
            }
        
            @Override
            protected void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("swagger-ui.html")
                        .addResourceLocations("classpath:/META-INF/resources/");
                registry.addResourceHandler("/webjars/**")
                        .addResourceLocations("classpath:/META-INF/resources/webjars/");
            }
         }
        

        我正在访问http://localhost:8080/context/swagger-ui.html,但使用该配置正确的 URL 是:http://localhost:8080/context/api/swagger-ui.html

        【讨论】:

          【解决方案5】:

          就我而言,问题的原因是:

          @ComponentScan(basePackageClasses = {ApplicationRoot.class })
          

          两次在两个 java 文件中。

          删除多余的一个后,问题就消失了。

          【讨论】:

            【解决方案6】:

            将 springfox-swagger2 和 springfox-swagger-ui 依赖升级到 2.9.2 并确保正确给出 basePackage

            return new Docket(DocumentationType.SWAGGER_2).select()
                        .apis(RequestHandlerSelectors
                            .basePackage("org.abc.xyz.controller"))
                        .paths(PathSelectors.regex("/.*"))
                        .build().apiInfo(apiEndPointsInfo());
            

            【讨论】:

              【解决方案7】:

              我没有使用 spring security 发生过这个问题。我的项目使用Maven Multiple Module,访问localhost:8080/swagger-ui.html时出现这个问题,首先我在SwaggerConf类中添加@EnableSwagger2,最后我将@EnableSwagger移动到SpringBoot Application类,这个问题就解决了。 第一:

              @Configuration
              @EnableSwagger2
              public class SwaggerConfig {
              
                  @Bean
                  public Docket api(){
                      return new Docket(DocumentationType.SWAGGER_2)
                              .select()
                              .apis(RequestHandlerSelectors.basePackage("com.zuoyan."))
                              .paths(PathSelectors.any())
                              .build();
                  }
              
              }
              

              最后:

               @SpringBootApplication(scanBasePackages = {"com.zuoyan.springboot.appmissionhall"})
               @EnableSwagger2
              public class ApplicationStartUpApplication {
                  public static void main(String[] args) {
                      SpringApplication.run(ApplicationStartUpApplication.class, args);
                  }
              
              }
              

              【讨论】:

                【解决方案8】:

                https://stackoverflow.com/a/56716898/13347514 的解决方案通过将 @EnableSwagger2WebMvc@Import(SpringDataRestConfiguration.class) 添加到主应用程序类解决了我的问题:

                @SpringBootApplication
                @EnableSwagger2WebMvc
                @Import(SpringDataRestConfiguration.class)
                public class MyApplication {
                
                    public static void main(String[] args) {
                        SpringApplication.run(MyApplication.class, args);
                    }
                
                }
                

                【讨论】:

                  【解决方案9】:

                  尝试使用端口 8080 - 在我将其更改为 8080 后为我工作

                  【讨论】:

                    【解决方案10】:

                    如果你没有指定任何特殊的组件扫描选项,如果你将带有@EnableSwagger2注解的类放在一个不在你的Spring Boot Application类(@SpringBootApplication)的层次结构中的包中,你将面临这个问题。

                    假设您的 Spring Boot 应用程序类在“de.oopexpert.app”中,然后将 @EnableSwagger2 注释类放入 ...

                    • de.oopexpert.app 可以工作
                    • de.oopexpert.app.config 将起作用
                    • de.oopexpert.config 将工作

                    您可以通过添加 @ComponentScan(basePackages = {"de.oopexpert"}) 来调整您的组件扫描选项,以指定层次结构的不同根。

                    【讨论】:

                      【解决方案11】:

                      我在 App 类中添加了@EnableSwagger2WebMvc 来修复它。我正在使用 Spring Boot 2.3.0.BUILD-SNAPSHOT 和 io.springfox 3.0.0-SNAPSHOT。 SpringFoxConfig 类保持不变。

                      package com.telixia.educare.academy;
                      
                      import org.springframework.boot.SpringApplication;
                      import org.springframework.boot.autoconfigure.SpringBootApplication;
                      
                      import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
                      
                      @EnableSwagger2WebMvc
                      @SpringBootApplication
                      public class AcademyApplication {
                      
                          public static void main(String[] args) {
                              SpringApplication.run(AcademyApplication.class, args);
                          }
                      
                      }
                      

                      【讨论】:

                        【解决方案12】:

                        这也可能是由pom.xml 中的springfox-swagger-uispringfox-swagger2 版本不匹配造成的,例如,如果您更新了一个但忘记更新另一个:

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

                        您需要确保springfox-swagger-uispringfox-swagger2 具有相同的版本。

                        【讨论】:

                          【解决方案13】:

                          在许多情况下,这是由于 Java 版本不兼容造成的。很多时候它不适用于Java 11,请尝试使用Java 8

                          【讨论】:

                            【解决方案14】:

                            首先确保添加了这两个依赖项,然后使用@EnableSwagger2注释您的主SpringBootApplication类,然后您的问题将得到解决。

                                <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>
                            

                            【讨论】:

                              【解决方案15】:

                              我在使用基本 Spring MVC 应用程序(没有 Spring Security)时遇到了同样的问题。

                              我换了

                                @Override
                                public void addResourceHandlers(ResourceHandlerRegistry registry) {
                                  registry.
                                      addResourceHandler("/swagger-ui/**")
                                      .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                                      .resourceChain(false);
                                }
                              

                                @Override
                                public void addResourceHandlers(ResourceHandlerRegistry registry) {
                                  registry.
                                      addResourceHandler("/swagger-ui/**")
                                      .addResourceLocations("classpath:/META-INF/resources/");
                                          registry.addResourceHandler("**/webjars/**")
                                              .addResourceLocations("classpath:/META-INF/resources/webjars/");
                              
                                }
                              

                              它成功了

                              【讨论】:

                                【解决方案16】:

                                在我的例子中,添加 springfox-spring-webmvc 依赖解决了这个问题:

                                   <dependency>
                                            <groupId>io.springfox</groupId>
                                            <artifactId>springfox-spring-webmvc</artifactId>
                                            <version>2.10.5</version>
                                        </dependency>
                                

                                【讨论】:

                                  【解决方案17】:

                                  只需清除浏览器缓存。它对我有用。

                                  我的 Swagger Docket Bean 配置文件:

                                  import org.springframework.context.annotation.Bean;
                                  import org.springframework.context.annotation.Configuration;
                                  import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
                                  import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
                                  
                                  import springfox.documentation.builders.PathSelectors;
                                  import springfox.documentation.builders.RequestHandlerSelectors;
                                  import springfox.documentation.spi.DocumentationType;
                                  import springfox.documentation.spring.web.plugins.Docket;
                                  import springfox.documentation.swagger2.annotations.EnableSwagger2;
                                  
                                  @Configuration
                                  @EnableSwagger2
                                  public class DocketBean implements WebMvcConfigurer {
                                  
                                      @Bean
                                      public Docket api() {
                                          return new Docket(DocumentationType.SWAGGER_2)
                                                  .select()
                                                  .apis(RequestHandlerSelectors.basePackage("com.swagger.demo"))
                                                  .paths(PathSelectors.any())
                                                  .build();
                                      }
                                  
                                      @Override
                                      public void addResourceHandlers(ResourceHandlerRegistry registry) {
                                          
                                          // enabling swagger-ui part for visual documentation
                                          registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
                                          registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
                                      }
                                  
                                  }
                                  

                                  POM 中的 Swagger 依赖项:

                                  <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>
                                  

                                  swagger-ui 网址:

                                  http://localhost:8080/swagger-ui.html

                                  【讨论】:

                                    猜你喜欢
                                    • 2019-10-10
                                    • 1970-01-01
                                    • 2016-07-09
                                    • 2021-04-06
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2019-12-21
                                    • 2019-11-15
                                    相关资源
                                    最近更新 更多