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

家住魔仙堡 提交于 2019-12-05 01:32:00

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

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

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

@EnableSwagger2

I am using swagger version

 <version>2.9.2</version>

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/**"

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

My specific security config for swagger is:

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.

EDIT 2018/04/10

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

To posterity:

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

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

This happened to me, I was using SpringBoot 1.5.16 and 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:

 @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

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

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

try with port 8080 - worked for me after i changed it to 8080

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

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

  • de.oopexpert.app will work
  • de.oopexpert.app.config will work
  • de.oopexpert.config will NOT work

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

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:

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

}
Guram Kankava

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

@ComponentScan(basePackageClasses = {ApplicationRoot.class })

twice in two java files.

after removing the extra one, the problem went away.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!