New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway #2191
Comments
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 The workaround is to make this route public : |
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. EDITWith a strange combination between @configuration and @EnableSwagger2 on SwaggerDocumentationConfig class, seems to have solved my issue. |
@cpoissonnier An |
We should NOT disable security checks for swagger resources - as it also have sensitive data that should NOT be shown to any unknown user |
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);
} |
Same here what the status of pull request? |
@evser thanks for sharing your configuration. You are absolutely correct about not unauthenticated users access to specification resources |
Maybe Help. I found that the Springboot Application Class need to add @EnableSwagger2 annotation. |
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.
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. |
Not sure. Would be great if you could share your repository |
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. |
@AlexRosier I think you need to protect the swagger resources as well starting from |
Hi! I follow the recomendations in this post and solved the problem. With the code bellow I can make calls to my rest API ignoring the This code protects:
In pom.xml
Class that extends WebSecurityConfigAdapter:
RestAuthenticationEntryPoint:
|
I am facing the same issue. I have my app protected with session cookie with SAML authentication. I can get in to /swagger-ui.html, which does a request to /swagger-resources/configuration/ui. This is failing due to the cookie not being attached to the call. If it navigate to /swagger-resources/configuration/ui directly, it works. Is there a way to configure swagger-ui.html to pass the authentication on in the ajax call? |
@zueski your issue should be fixed in the upcoming release of 2.9.0 |
Thanks @dilipkrish -- In the meantime, I have added this to my application.yml to work around this:
|
@zueski FYI 2.9.0 is released |
@dilipkrish Not see it in maven yet... need wait till maven central publish? |
@Hronom Its available in jcenter for now. <repositories>
<repository>
<id>jcenter</id>
<url>https://jcenter.bintray.com/</url>
</repository>
</repositories> There is an issue getting it released in maven central that Im working through. |
I've fought this issue a lot (due to bad logging capabilities I believe) and will share my findings here. My setup:
Spring boot 2.0.0.RELEASE dependencyManagement { I have two filterchains: Swagger filter config:
// AUTH_WHITELIST as mentioned above in this thread - without "/error" REST filter NOTE: Hope this helps ya out! :) |
@CarstenHS thank you for sharing. This is probably one of the most sought after solutions for problems related to not rendering swagger-ui. |
Nothing related to Spring Security configuration, but I had the same issue and I fixed it, by changing this :
to
Without adding restriction on base package to scan, in annotation 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. |
Thanks for letting us know @lcareto! |
If after all attempt, your issue is not solved try to remove the property
in your spring boot application.properties. Hope that will helps you guys. ;) |
Thanks for the tip @HamedKaramoko |
I had to apply |
@dschulten just FYI, it is but it is still not written in stone (still a SNAPSHOT), If the usability implies it remain for upgrade paths etc. Im open to bringing it back. |
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. |
@luksrn thanks for clarifying! |
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. |
It worked for me after adding above lines. But what if I need some security to my applications. |
This solved my issue, thank you for sharing Bro. |
this was helpful for me, using my own swagger.json with springfox-swagger-ui: |
@evser |
Here it's worked : http://localhost:8080/swagger-ui/index.html |
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 |
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:
And this is my SecurityConfig.java :
|
After updating Swagger to 2.8.0, I started to experience this issue. I never faced this before.
#1865
Does anyone either?
The text was updated successfully, but these errors were encountered: