Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow anonymous access to springdoc-openapi-ui with Spring Security

How to allow anonymous access to springdoc-openapi-ui (OpenAPI 3.0 /swagger-ui.html) in a Spring Boot application secured by Spring Security?

like image 914
Evgeniy Khyst Avatar asked Jan 24 '20 14:01

Evgeniy Khyst


3 Answers

To use springdoc-openapi-ui /swagger-ui.html, allow anonymous access to the following endpoints in the WebSecurityConfigurerAdapter using permitAll method:

  • /v3/api-docs/**
  • /swagger-ui/**
  • /swagger-ui.html

Example:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http.
        .authorizeRequests()
        .antMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()
        .anyRequest().authenticated()
        .and()
        .httpBasic(); //or anything else, e.g. .oauth2ResourceServer().jwt()
  }
}

Make sure a project has the following dependencies:

  • org.springdoc:springdoc-openapi-ui
  • org.springdoc:springdoc-openapi-security
like image 58
Evgeniy Khyst Avatar answered Nov 11 '22 19:11

Evgeniy Khyst


Additionally to Evgeniy's answer, I'd add the proper configuration to avoid conflicts with document fetching used in Swagger's UI (such js, html, images and other files), also in the SecurityConfig class like this:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   //Other configuration methods
   
   @Override
   public void configure(WebSecurity web) {
    web.ignoring()
    .antMatchers("/v3/api-docs/**", "/swagger-ui/**");
   }
}

Without this configuration, even though the UI looks like It's loaded, a 401: Unauthorized may arise on the background calls when loading the above mentioned files.

like image 33
batero Avatar answered Nov 11 '22 21:11

batero


For obtaining access in spring webflux you have to do the following, tested with spring-doc version 1.5.2:

The swagger webpage was failing on html resources with the path /webjars/swagger-ui.

@Configuration
@EnableWebFluxSecurity
public class WebSecurityConfig {

  @Bean
  SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
    return http.
        .authorizeExchange()
        .pathMatchers(
            "/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html", "/webjars/swagger-ui/**")
        .permitAll()
        .anyExchange()
        .authenticated()
        .and()
        .build();
  }
}
like image 44
jkamcc Avatar answered Nov 11 '22 20:11

jkamcc