springfox: Can't test the configuration 404 not found

I can’t test the configuration for the Swagger API in Spring Boot Application using http://localhost:8080/forest/v2/api-docs It is showing 404 not found

Also, http://localhost:8080/forest/swagger-ui.html is showing 404 not found along with a 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-docs then the base url is http://example.org/api/. Please enter the location manually:

Springfox 2.7.0 Swagger core 1.5.13

pom.xml


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

SwaggerConf.java


@EnableSwagger2
public class SwaggerConf {

   @Bean
   public Docket newsApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("greetings")
                .apiInfo(apiInfo())
                .select()
                .paths(regex("/greeting.*"))
                .build();
     }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring REST Sample with Swagger")
                .description("Spring REST Sample with Swagger")
                .termsOfServiceUrl("http://www-03.ibm.com/software/sla/sladb.nsf/sla/bm?Open")
                .license("Apache License Version 2.0")
                .licenseUrl("https://github.com/IBM-Bluemix/news-aggregator/blob/master/LICENSE")
                .version("2.0")
                .build();
    }
}

Web.xml

   
<servlet>
    <servlet-name>servletForest</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextAttForest</param-name>
      <param-value>org.springframework.web.context.WebApplicationContext.ROOT</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>servletForest</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 79 (24 by maintainers)

Most upvoted comments

We too are experiencing the same error. Any guidance would be fantastic. Thanks!

Hi,

I faced the same problem, I could see the /v2/api-docs but not the swagger-ui.html. I fixed it adding this to my WebSecurityConfigurerAdapter class

@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui/**", "/swagger-resources/**", "/configuration/security/**", "/swagger-ui.html", "/webjars/**");
    }

Kind Regards Jose

Had the same issue and resolved it by following the spring security advice above, but not only for api-docs and swagger-ui.html, but also for swagger-resources and webjars.

Example: antmatchers

I see those maven dependencies under my project which got added by default by keeping those two dependencies on the pom file.

<dependency>
<groupId>io.springfox</groupId>

<artifactId>springfox-swagger2</artifactId>

<version>${springfox-swagger2.version}</version>
</dependency> <dependency>
<groupId>io.springfox</groupId>

<artifactId>springfox-swagger-ui</artifactId>

<version>${springfox-swagger-ui.version}</version>
</dependency>

On Tue, Jul 4, 2017 at 12:18 PM, Dilip Krishnan notifications@github.com wrote:

@dpatra1 https://github.com/dpatra1 it should be available @ http://localhost:8080/swagger-ui.html if you don’t have a dynamic servlet mapping. If not report back. Cant tell without specifics. Regarding dependencies it is going to make your life easier, and not necessarily solve your problem.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/springfox/springfox/issues/1865#issuecomment-312937265, or mute the thread https://github.com/notifications/unsubscribe-auth/AMLEEC0KWCAX2I74a03xWvH3ql03mpbxks5sKo_wgaJpZM4N41Nr .

– Debapriya Patra debapriya.patra@gmail.com 9741500237

Fair enough. It is just a few changes to springfox.js, so that is logs errors to console.log, stops keeping poping-up, cancel works…

Hi friends i solve this problem with @Configuration in my configuration class. I hope that this help you. https://github.com/luansousa26/java8-default-crud-application

package com.luan.java8defaultcrudapplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;
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;
@EnableSwagger2
@Configuration
public class SwaggerConfig {
	@Bean
		public Docket detalheApi() {
	 
			Docket docket = new Docket(DocumentationType.SWAGGER_2);
	 
			docket
			.select()
			.apis(RequestHandlerSelectors.basePackage("com.luan"))
			.paths(PathSelectors.any())
			.build()
			.apiInfo(this.informacoesApi().build());
	 
			return docket;
		}
	 
		private ApiInfoBuilder informacoesApi() {
	 
			ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder();
	 
			apiInfoBuilder.title("Api-Crud");
			apiInfoBuilder.description("Default Crud API for Study proposes.");
			apiInfoBuilder.version("1.0");
			apiInfoBuilder.termsOfServiceUrl("Free use.");
			apiInfoBuilder.license("License - Open Source");
			apiInfoBuilder.licenseUrl("https://github.com/luansousa26");
	 
			return apiInfoBuilder;
	 
		}
	}

with the @configuration image

Without configuration image

I too have the same issue. My app is in Scala. The code compiles and runs but I can’t hit http://locathost:8080/swagger-ui.html I get a 404. on the other hand http://localhost:8080/v2/api-docs works beautifully!

I have dependencies ( I had to downgrade to 2.6,1 from 2.7.0):

compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.6.1'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.1'

In addition, I am not using Spring Security and have added only this class:

package com.jsimone.config

import java.util.ArrayList

import org.springframework.context.annotation.{Bean, Configuration}
import springfox.documentation.builders.PathSelectors.regex
import springfox.documentation.builders.{PathSelectors, RequestHandlerSelectors}
import springfox.documentation.service.{ApiInfo, Contact, VendorExtension}
import springfox.documentation.spi.DocumentationType
import springfox.documentation.spring.web.plugins.Docket
import springfox.documentation.swagger2.annotations.EnableSwagger2


@Configuration
@EnableSwagger2
class SwaggerConfig {
  @Bean
  def api(): Docket = {
    new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.basePackage("com.jsimone.controller"))
      .paths(regex("/*"))
      .build()
      .apiInfo(metaData)
  }

  private def metaData: ApiInfo = {
    new ApiInfo(
      "Spring Boot Scala REST API Application Example",
      """A sample Scala project using Spring Boot and providing examples of validation and end-point testing.
        for more information on the OpenAPI Specification (aka Swagger) used herein see
        <a href=http://openapi-specification-visual-documentation.apihandyman.io/>OpenAPI Visual Documentation</a>""",
      "1.0.0",
      "Terms of service",
      new Contact("Joseph Simone", "http://github.com/jesimone57", "jesimone57@yahoo.com"),
      "Apache License Version 2.0",
      "https://www.apache.org/licenses/LICENSE-2.0")
  }
}

The project is available in github here:

https://github.com/jesimone57/spring_boot_scala_rest_example

Any help is greatly appreciated. I created an open_api.yaml spec for the project (in spec folder), so I wanted to see if I could get the annotations to work. But I can’t after many hours of playing around with it.

I have met the same problem and fixed it by adding /swagger-ui.html** to permitAll. The ** is nessary, because swagger will request /swagger-ui.html#/, and without ** spring security will filter the request.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/security", "/swagger-ui.html**", "/webjars/**").permitAll()
            .anyRequest().authenticated()

FYI

I had the same problem, and fixed it.

I have an spring boot API project, and want to add swagger-ui as docs. The reason it didn’t work is because I have requests verification, such as “AccessToken” verification.

Exclude /v2/api-docs from verification makes the API returns expected JSON. But swagger-ui.html still return JS errors.

@madhumvgr mentions that visit swagger-ui.html redirects to swagger-resources/configuration/ui. So I exclude /swagger-resources/xx from verification. And finally, Swagger UI works now.

Hope it helps.

Hi guys, I was having the same exact problem as many of you have experienced. In case it should be of any help to anyone here, this is how my entire WebSecurity class looks like. It is written in Groovy and I am using Okta’s JwtVerifier for authorization:

import com.xxx.subscription.service.JwtAuthorizationFilter
import com.xxx.subscription.service.JwtService
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter

import javax.annotation.Resource

@Configuration //Cannot use @EnableWebSecurity here... it causes Swagger2 plugin to NOT work (the /v2/api-docs works fine, but the swagger-ui.html does not display correctly)
class WebSecurity extends WebSecurityConfigurerAdapter {

    @Value('${apiDocumentationUrl}')
    String apiDocumentationUrl

    @Value('${apiDocumentationUrl2}')
    String apiDocumentationUrl2

    @Resource
    JwtService jwtService

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        JwtAuthorizationFilter jwtAuthorizationFilter = new JwtAuthorizationFilter(super.authenticationManager())
        jwtAuthorizationFilter.jwtService = jwtService

        httpSecurity.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.GET, apiDocumentationUrl).permitAll()
                .antMatchers(HttpMethod.GET, apiDocumentationUrl2).permitAll()
                /*
                * NOTE TO SELF: Do NOT use anyRequest().authenticated() here!! It will cause the Swagger2 plugin to NOT work. when you go to the swagger-ui.html, it will keep asking you the path...
                * This apparently, is a fairly common problem: https://github.com/springfox/springfox/issues/1865
                * */
                .antMatchers(HttpMethod.GET, '/subscriptions/**').authenticated()
                .and()
                .addFilter(jwtAuthorizationFilter)
    }
}

Hi All,

I am also stuck at localhost/swagger-ui.html, I see the same error as mentioned before by dpatra1 on Jun 26. I spent lot of time to integrate swagger to spring mvc application. https://user-images.githubusercontent.com/12764176/27525730-16a33b82-59f5-11e7-9d47-3d76d1ad47b0.png In browser console I see 404 resource not found error. Same for other urls like localhost/v2/api-docs and swagger-resources. My code changes are as below: springfox-swagger2 – <version>2.6.0</version> Same error with springfox-swagger2 version 2.7.0 also.

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

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

applicationContext.xml

 	<bean id="mySwaggerConfig" class="com.xxx.yy.swagger.MySwaggerConfig"/>
 	<bean id="webSecurityConfiguration" class="com.xxx.yy.swagger.WebSecurityConfiguration"/>

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui/**","/swagger-resources/**", "/configuration/security/**","/swagger-ui.html", "/webjars/**");
	}
}

securityconfig

<security:intercept-url pattern="/swagger-ui.html" access="permitAll" requires-channel="http" />
<security:intercept-url pattern="/v2/api-docs" access="permitAll" requires-channel="http" /
<security:intercept-url pattern="/configuration/ui" access="permitAll" requires-channel="http" />
<security:intercept-url pattern="/swagger-resources" access="permitAll" requires-channel="http" />
<security:intercept-url pattern="/configuration/security" access="permitAll" requires-channel="http" />
<security:intercept-url pattern="/webjars/**" access="permitAll" requires-channel="http" />

Any help reference docs appreciated…

After some tests, in my case I didn’t have to touch the Spring Security configuration, but rather the class filtering the requests (... extends OncePerRequestFilter), in particular the method doFilterInternal(), where a redirection to the webapp root was happening if the URL didn’t start with /api and wasn’t a filename.

@inad9300 Sorry about that, you are correct! I lost the previous method calls when copy/pasting the example code. I’ve updated the example in my comment.