Skip to content

Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway #2191

Closed

Description

@evser

After updating Swagger to 2.8.0, I started to experience this issue. I never faced this before.
#1865
Does anyone either?

Activity

  1. cpoissonnier commented on Jan 17, 2018

    @cpoissonnier

    Make sure that all query are ok in developer console, I have the same issue, some of my queries return 403.

    In my project, Swagger is behind basic auth (to prevent swagger to be public), but /swagger-resources/** routes are not called with Authorization header since I updated to Springfox 2.8.0

    The workaround is to make this route public :
    .antMatchers("/swagger-resources/**").permitAll()

  2. goodlifeinc commented on Jan 17, 2018

    @goodlifeinc

    Well I am using Swagger 2.7.0 and this fix doesn't help.

    Here is my security setup. Actuator endpoints are behind basicAuthentication.

    http
    	.csrf().disable()
    		.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    	.and()
    		.authorizeRequests()
    			.antMatchers(actuatorPath + "/**").authenticated()
    	.and()
    		.httpBasic()
    	.and()
    		.authorizeRequests()
    			.anyRequest().permitAll();

    Stangest thing is same config in another project with same dependencies works fine.

    EDIT

    With a strange combination between @configuration and @EnableSwagger2 on SwaggerDocumentationConfig class, seems to have solved my issue.

  3. kasecato commented on Jan 18, 2018

    @kasecato
    Contributor

    @cpoissonnier An Authorization header will be added on the same-origin by #2189.

  4. evser commented on Jan 20, 2018

    @evser
    Author

    We should NOT disable security checks for swagger resources - as it also have sensitive data that should NOT be shown to any unknown user

  5. evser commented on Jan 20, 2018

    @evser
    Author

    BTW, here are my settings (I use cookies-based auth in my browser):

           protected void configure(HttpSecurity http) throws Exception {
    		http.authorizeRequests()
    				.anyRequest().authenticated()
    				.and().exceptionHandling().accessDeniedHandler(new AccessDeniedHandlerImpl())
    				.and().logout().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
    				.and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    				.and()
    				.addFilterBefore(ssoFilter(ApplicationConfiguration.API_BASE_PATH + "/login"), BasicAuthenticationFilter.class)
    				.requiresChannel().anyRequest().requireSecure();
    	}
    
    	@Bean
    	public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
    		FilterRegistrationBean frb = new FilterRegistrationBean();
    		frb.setFilter(filter);
    		frb.setOrder(SecurityProperties.DEFAULT_FILTER_ORDER);
    		return frb;
    	}
    
    	@Bean
    	@ConfigurationProperties("oauth2.client")
    	public OAuth2ProtectedResourceDetails authDetails() {
    		return new AuthorizationCodeResourceDetails();
    	}
    
    	@Bean
    	public SecurityConfiguration swaggerSecurityConfiguration() {
    		return new SecurityConfiguration("client-id", "client-secret", "realm",
    				"", "{{X-XSRF-COOKIE}}", ApiKeyVehicle.HEADER, "X-XSRF-TOKEN", ",");
    	}
    
    	private Filter ssoFilter(String path) {
    		OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter = new OAuth2ClientAuthenticationProcessingFilter(path);
    		OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(authDetails(), oauth2ClientContext);
    		DefaultRedirectStrategy defaultRedirectStrategy = new DefaultRedirectStrategy();
    		oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate);
    		oAuth2ClientAuthenticationFilter.setTokenServices(resourceServerTokenServices);
    		oAuth2ClientAuthenticationFilter.setAuthenticationSuccessHandler(
    				(request, response, authentication) -> {
    					String redirectUrl = request.getParameter(REDIRECT_URL_PARAM);
    					if (redirectUrl == null) {
    						redirectUrl = DEFAULT_REDIRECT_URL;
    					} else {
    						if (!redirectUrlValidator.validateRedirectUrl(redirectUrl)) {
    							request.setAttribute(MESSAGE_ATTRIBUTE_NAME,
    									messageSource.getMessage("ivalid.redirect.url", new String[] { redirectUrl }, LocaleContextHolder.getLocale()));
    							response.sendError(HttpStatus.FORBIDDEN.value());
    						}
    					}
    					defaultRedirectStrategy.sendRedirect(request, response, redirectUrl);
    				});
    		return oAuth2ClientAuthenticationFilter;
    	}

    And Docket:

    	@Bean
    	public Docket api() throws IOException, URISyntaxException {
    		final List<ResponseMessage> globalResponses = Arrays.asList(
    				new ResponseMessageBuilder()
    						.code(200)
    						.message("OK")
    						.build(),
    				new ResponseMessageBuilder()
    						.code(400)
    						.message("Bad Request")
    						.build(),
    				new ResponseMessageBuilder()
    						.code(500)
    						.message("Internal Error")
    						.build());
    		final ApiInfo apiInfo = new ApiInfo("REST API", new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(CHANGELOG_FILENAME)))
    				.lines()
    				.collect(Collectors.joining(System.lineSeparator())),
    				"1.0.0-RC1", "", new Contact("team", "", "bla@bla.com"), "", "", Collections.emptyList());
    		return EnvironmentUtils
    				.applyIfNotStaging(
    						new Docket(DocumentationType.SWAGGER_2),
    						docket -> docket.securitySchemes(Arrays.asList(new ApiKey("Token Access", HttpHeaders.AUTHORIZATION, In.HEADER.name()))))
    				.useDefaultResponseMessages(false)
    				.globalResponseMessage(RequestMethod.GET, globalResponses)
    				.globalResponseMessage(RequestMethod.POST, globalResponses)
    				.globalResponseMessage(RequestMethod.DELETE, globalResponses)
    				.globalResponseMessage(RequestMethod.PATCH, globalResponses)
    				.select()
    				.apis(RequestHandlerSelectors.basePackage("com.controller"))
    				.build()
    				.apiInfo(apiInfo)
    				.directModelSubstitute(Temporal.class, String.class);
    	}
  6. Hronom commented on Jan 26, 2018

    @Hronom

    Same here what the status of pull request?
    My application is protected by basic auth using api gateway.

  7. dilipkrish commented on Jan 30, 2018

    @dilipkrish
    Member

    @evser thanks for sharing your configuration. You are absolutely correct about not unauthenticated users access to specification resources

  8. crazy-airhead commented on Feb 12, 2018

    @crazy-airhead

    Maybe Help. I found that the Springboot Application Class need to add @EnableSwagger2 annotation.

  9. seetharamani commented on Mar 9, 2018

    @seetharamani

    Does this issue have been figured out?? Once i upgraded to 2.8.0 from 2.6.1, the swagger ui started showing the error "Unable to infer base url".

    When I look at debug logs, i do see this line.

    {"category":"org.springframework.boot.web.filter.OrderedRequestContextFilter","severity":"DEBUG","text":"Bound request context to thread: Request(GET //localhost:10780/my-service/api/null/null/swagger-resources)@5689340d"},"v":"1"}

    Why the base url for the swagger-resources are messed up - no idea! I tried debugging, and when i step in I do see the context path of my application is right, which is /my-service.

    Any help is appreciated.

  10. dilipkrish commented on Mar 10, 2018

    @dilipkrish
    Member

    Not sure. Would be great if you could share your repository

  11. AlexRosier commented on Mar 16, 2018

    @AlexRosier

    I have the same issue using spring security with basic authentication. What avoided the issues is adding

    protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers(
                                    "/v2/api-docs",
                                     "/swagger-resources", 
                                    "/swagger-resources/configuration/ui", 
                                    "/swagger-resources/configuration/security")
                    .permitAll()

    But this removes all security of those endpoints. An other solution is setting the Authorization header with the basic authentication.
    But what I think should happen is the basic authentication pop-up is shown before the "Unable to infer base url" pop-up

  12. dilipkrish commented on Mar 17, 2018

    @dilipkrish
    Member

    @AlexRosier I think you need to protect the swagger resources as well starting from swagger-ui

  13. 18 remaining items

  14. luksrn commented on Dec 6, 2018

    @luksrn

    Hey guys, in my case it was a ResponseBodyAdvice that changed the response body of /v2/api-docs endpoint. I fixed the advice and the ui was rendered as expected.

  15. dilipkrish commented on Dec 17, 2018

    @dilipkrish
    Member

    @luksrn thanks for clarifying!

  16. akuma8 commented on Jan 13, 2019

    @akuma8

    Sorry to open this issue but I am facing the same issue just after changing the static resource path from spring.mvc.static-path-pattern=/** to spring.mvc.static-path-pattern=/app-resources/**.
    swagger

  17. MehmetMelik commented on Jan 16, 2019

    @MehmetMelik

    Clearing the browser cache in chrome fixed the issue. This may sound weird but this is what solved the problem in my case.

  18. sidhjhawar commented on Jun 28, 2019

    @sidhjhawar

    Clearing the browser cache in chrome fixed the issue. This may sound weird but this is what solved the problem in my case.

    Yes, I just used incognito mode to open the swagger-ui and it worked fine.

  19. rakesh415 commented on Aug 1, 2019

    @rakesh415

    Thanks @dilipkrish -- In the meantime, I have added this to my application.yml to work around this:

    security:
      ignored: /swagger-resources/**
    

    It worked for me after adding above lines. But what if I need some security to my applications.

  20. MohSalah90 commented on Aug 3, 2019

    @MohSalah90

    Nothing related to Spring Security configuration, but I had the same issue and I fixed it, by changing this :

    @RestControllerAdvice
    public class MyResponseBodyAdvice implements ResponseBodyAdvice<ResponseWrapper> {
    }
    

    to

    @RestControllerAdvice("my.super.package")
    public class MyResponseBodyAdvice implements ResponseBodyAdvice<ResponseWrapper> {
    }
    

    Without adding restriction on base package to scan, in annotation @RestControllerAdvice, I guess it scans also all the package dependencies, and tries to cast all the ResponseBody to the defined type (in my case ResponseWrapper).

    I'm running Spring Boot 2.0.2.RELEASE and Swagger 2.8.0; Springfox update to 2.9.0 didn't fix my problem.

    This solved my issue, thank you for sharing Bro.

  21. hacki11 commented on Aug 30, 2019

    @hacki11

    this was helpful for me, using my own swagger.json with springfox-swagger-ui:
    indrabasak/springfox-ui-from-json-example#2

  22. JakeWoki commented on Jul 5, 2021

    @JakeWoki

    @evser
    using Spring Security,how to add login/logout document?

  23. MurilloNacfur commented on Aug 6, 2021

    @MurilloNacfur
  24. hasitha3rd commented on Jan 5, 2022

    @hasitha3rd

    I was stuck for a day with this issue. My issue was incorrect port configuration. Check your application.yml/application.properties file for port configuration. There I had mistakenly added both
    server.port , management.server.port with different values 🤣 .

  25. miladmofidi commented on Apr 26, 2022

    @miladmofidi

    I have the same issue, when I open swagger UI URL: http://192.168.32.241:31650/swagger-ui.html , appear this error I read the comments but I could not solve my issue.

    my SwaggerConfig.java is:

    `@Configuration
    @EnableSwagger2
    public class SwaggerConfig
    {
        public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.some.core.controller";
    
        @Bean
        public Docket SpringFoxConfig()
        {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
                    .paths(regex("/tmf-api/ServiceActivationAndConfiguration/v4/service.*"))
                    .build()
                    .apiInfo(metaData()).securitySchemes(Collections.singletonList(apiKey()))
                    .securityContexts(Collections.singletonList(securityContext()));
        }
    
        private ApiInfo metaData()
        {
            return new ApiInfoBuilder().version("1.0.0").title("title")
                    .description("desc").contact(
                            new Contact("contact",
                                        "contact"))
                    .build();
        }
    
        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("JWT", authorizationScopes));
        }
    
        private ApiKey apiKey()
        {
            return new ApiKey("JWT", "Authorization", "header");
        }
    }
    `
    

    And this is my SecurityConfig.java :

    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter
    {
    
        @SuppressWarnings("findsecbugs:SPRING_CSRF_PROTECTION_DISABLED")
        @Override
        protected void configure(HttpSecurity http) throws Exception
        {
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
            corsConfiguration.setAllowedOrigins(List.of("*"));
            corsConfiguration
                    .setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PUT", "OPTIONS", "PATCH", "DELETE"));
    
            http.authorizeRequests().antMatchers("/**").permitAll().anyRequest()
                    .authenticated().and().csrf().disable().cors().configurationSource(request -> corsConfiguration)
            ;
        }
    }
    
  26. added a commit that references this issue on Mar 4, 2024
    8e37f4e
  27. VinayakKulkarniTR commented on Mar 28, 2024

    @VinayakKulkarniTR

    I have resolve the issue by downgrading the Swagger version and Implementing swagger in Spring MVC. But facing another issue with @EnableSwagger2. If is use this annotation i am getting error as given below -
    Caused by: java.lang.NoSuchMethodException: springfox.documentation.spring.web.SpringfoxWebMvcConfiguration$$EnhancerBySpringCGLIB$$f6a2d0cd.jsonSerializer()

    Has anyone faced this error before? Could any suggest the solution for this?

  28. Greko2017 commented on Aug 14, 2025

    @Greko2017

    Maybe Help. I found that the Springboot Application Class need to add @EnableSwagger2 annotation.

    This solved my issue thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions