14

I am enable swagger2 by @EnableSwagger2. However, when I try to hit "/swagger-ui.html", it first hit my Authentication Filter. Then, I wrote the following code to bypass the authentication check

String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);
if ("/swagger-ui.html".equalsIgnoreCase(resourcePath)) {
     filterChain.doFilter(request, response);
}

I can see the filterChain.doFilter(request, response); was hit. However, when I let the debug go, it returns a page with information below

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Apr 04 15:41:50 EDT 2018
There was an unexpected error (type=Unauthorized, status=401).
No message available

Any idea, guys?

Laodao
  • 1,547
  • 3
  • 17
  • 39
  • do you need to add "/swagger-ui.html" as an exception from filtere configuration? that could be the situation with Oauth2 – Georgi Stoyanov Apr 04 '18 at 21:32
  • @GeorgiStoyanov, how can I do that? I put `security.basic.enabled = false` in the application.properties, same result. – Laodao Apr 04 '18 at 21:43
  • Think you can add your own `WebSecurityConfig extends WebSecurityConfigurerAdapter`, override `configure(WebSecurity web)` method and there put `web.ignoring().antMatchers("/swagger-ui.html")` ofc annotate that class with `@Configuration` – Georgi Stoyanov Apr 05 '18 at 06:35
  • Thanks a lot, @GeorgiStoyanov. It works perfectly. Could you please copy your comments as an answer so that I can accept it. Thanks again. – Laodao Apr 05 '18 at 15:07

5 Answers5

9

I encountered the same issue in my project and discovered this solution, so first add this config file to the project

package bla.bla.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

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

}

and then add this code block to you WebSecurityConfig

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

my problem fixed

source : swagger.io

  • This worked for me, thx. Do you or does anyone know why "/swagger-ui.html/**" isn't enough? – msTam Apr 29 '21 at 14:04
  • @msTam - when you hit swagger-ui-.html , all other supported files like css, jars also gets loaded and they are also behind the security and if you dont bypass them then page will not be loaded and it will still prompt for authentication. – SarangRN Jan 20 '23 at 06:44
5

Think you can add your ownWebSecurityConfig extends WebSecurityConfigurerAdapter, than override configure(WebSecurity web) method and there put web.ignoring().antMatchers("/swagger-ui.html") ofc annotate that class with @Configuration

Georgi Stoyanov
  • 469
  • 1
  • 5
  • 24
2

I have the same error and I add this code inside the class websecurityConfig

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests().antMatchers("/api/auth/**").permitAll() 
                .antMatchers("/api/test/**").permitAll() // permit the class of test
                .antMatchers("/**").permitAll() // permit all the routers after swagger-ui.html
                .anyRequest().authenticated();

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
  • It's unclear to me whether you are saying that the added code resolved the problem, or if this answer in fact falls into an "I have this problem, too" category. If indeed your code change has resolved the OP's problem, in order to avoid having your answer downvoted, I would suggest rewording it. – Kenn Sebesta Sep 23 '20 at 13:11
0

As answered by Georgi Stoyanov , adding that much code removed Whitelabel Error Page error but my swagger UI home page was blank as there was 401 issue in loading some css & js files. Swagger-ui with Spring security

Also, important point that I want to mention is that my swagger UI was working for Weblogic deployment without above code (only HttpSecurity override was enough ) and I was facing issue only when running app in embedded tomcat.

Spring Boot Version : 1.5.2.RELEASE

SpringFox Version 2.8.0

So I had to made code changes as answered by me in linked question to load all CSS & JS files also.

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
0

I had the same problem and this was my solution.

if do you have a Spring security config, you must to give authorization at all urls that swagger needs

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
        .csrf()
        .disable()
        .authorizeRequests()
        .antMatchers(HttpMethod.POST,"/api/loggin").permitAll()
        .antMatchers(HttpMethod.GET,"/swagger-resources/**").permitAll()
        .antMatchers(HttpMethod.GET,"/swagger-ui/**").permitAll()
        .antMatchers(HttpMethod.GET,"/v2/api-docs").permitAll()
        .anyRequest()
        .authenticated();           
}

and in your class main you shuld to add this notation

@EnableSwagger2

and finally in yor pom.xml this dependencies.

<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

for use http://localhost:8090/swagger-ui/