spring Springfox swagger-ui.html 无法推断基本 URL - 由缺少 cookie 引起

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49155420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:35:21  来源:igfitidea点击:

Springfox swagger-ui.html unable to infer base URL - Caused by missing cookies

springspring-bootswaggerswagger-uispringfox

提问by Arnab Gupta

We have our Spring Boot services behind an API Gateway. With an earlier version of Springfox - 2.1.2 we had no issues in loading the swagger-ui.htmlpage. This worked with Spring Boot 1.4.3.RELEASE. From then, we have upgraded to Boot 1.5.7 and upgraded Springfox to 2.8.0.

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

Now if we load the page we get an alert box with the following long message.

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

Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docsthen the base url is http://example.org/api/. Please enter the location manually

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

I got some hints searching online, but it does not seem those situations apply to us. For one, if I simply revert back the versions, it starts working again through the same API Gateway.

我在网上搜索得到了一些提示,但这些情况似乎不适用于我们。一方面,如果我简单地恢复版本,它会通过相同的 API 网关再次开始工作。

Tracking the traffic, it seems calls to three XHR resources made by the .html page is causing issues. These are returning 401 from our API gateway. And the reason they return 401 is because the cookies are not passed along.

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

The three calls are:

这三个调用是:

If I load these URLs as pure browser requests - they work - because cookies are sent.

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

I doubt if CORS applies since the HTML is being served from the same address as the swagger JSON and actual service calls.

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

Any idea why this may be happening? Anybody faced similar issues? Suggestions for workaround? Thanks much in advance.

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

回答by panksy2k

Add in the security config -- following URLS that are skipped for authentication ::

添加安全配置——以下 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);
}

回答by Arindam

Adding below annotation at the spring boot class resolved this issue for me.

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

@EnableSwagger2

@EnableSwagger2

I am using swagger version

我正在使用 swagger 版本

 <version>2.9.2</version>

回答by Marco Blos

SEE EDIT BELOW

请参阅下面的编辑

Do you use spring security?

你使用弹簧安全吗?

If yes, probably you skip some resources like this (right?): "/swagger-resources/**", "/swagger-ui.html", "/v2/api-docs", "/webjars/**"

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

Try to change it "/swagger-resources/**"to "**/swagger-resources/**".

尝试将其更改"/swagger-resources/**""**/swagger-resources/**".

My specific security config for swagger is:

我对 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;
}

If you need/want I can send a sample project to GitHub to you know more about my security/swagger configs.

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

EDIT 2018/04/10

编辑 2018/04/10

This problem is caused by a wrong version in springfox. See this issue on github to solve the problem.

这个问题是springfox版本错误导致的。在github上看到这个问题来解决问题

To posterity:

给后人:

In pom.xml

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

Class that extends WebSecurityConfigAdapter:

扩展 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:

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");
    }
}

回答by carolnogueira

This happened to me, I was using SpringBoot 1.5.16 and Springfox 2.9.1.

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

In my application.properties, I had defined server.servlet-path=/api, but, somehow, the swagger-ui was ignoring the value defined. I've tried so many different way to make this work, and finally I found a workaround:

在我的 中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/");
    }
 }

I was accessing http://localhost:8080/context/swagger-ui.html, but with that configuration the correct URL is: http://localhost:8080/context/api/swagger-ui.html

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

回答by Harshavardhan

Upgrade springfox-swagger2 and springfox-swagger-ui dependencies to 2.9.2 and also ensure the basePackage is given properly

将 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());

回答by Guram Kankava

In my case, the cause of the problem was having:

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

@ComponentScan(basePackageClasses = {ApplicationRoot.class })

twice in two java files.

在两个java文件中两次。

after removing the extra one, the problem went away.

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

回答by oopexpert

If you do not specify any special component scan options you will face this problem if you put the class with the @EnableSwagger2 annotation in a package that is not in the hierarchy of your Spring Boot Application class (@SpringBootApplication).

如果您没有指定任何特殊的组件扫描选项,如果您将带有 @EnableSwagger2 注释的类放在不在 Spring Boot 应用程序类 (@SpringBootApplication) 的层次结构中的包中,您将面临此问题。

Assume your Spring Boot Application class in "de.oopexpert.app", then putting @EnableSwagger2 annotated class in ...

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

  • de.oopexpert.app will work
  • de.oopexpert.app.config will work
  • de.oopexpert.config will NOTwork
  • de.oopexpert.app 将工作
  • de.oopexpert.app.config 将工作
  • de.oopexpert.config将工作

You may adapt your component scan options by adding @ComponentScan(basePackages = {"de.oopexpert"}) to specify a different root of the hierarchy.

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

回答by Zuoyan

I don't use spring security happened this question. My Project Use Maven Multiple Module, When access to the localhost:8080/swagger-ui.html happend this question, First I add @EnableSwagger2 in the SwaggerConf class ,Last I move @EnableSwagger to SpringBoot Application class ,this question is solved. First:

我不使用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();
    }

}

Finally:

最后:

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

}

回答by Nditah

I added @EnableSwagger2WebMvcto the App class to fix it. I am using Spring boot 2.3.0.BUILD-SNAPSHOT and io.springfox 3.0.0-SNAPSHOT. SpringFoxConfig class stays the same.

我添加@EnableSwagger2WebMvc到 App 类来修复它。我正在使用 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);
    }

}

回答by Kirill Simonov

This could also be caused by the springfox-swagger-uiand springfox-swagger2versions mismatch in the pom.xml, for example, if you updated one but forgot to update another:

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

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

You need to make sure springfox-swagger-uiand springfox-swagger2have the same version.

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