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

- 9,236
- 7
- 38
- 65
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:

- 9,236
- 7
- 38
- 65
-
1I also had to do this: https://github.com/springdoc/springdoc-openapi/issues/230#issuecomment-563485698 – Andrew Puglionesi Dec 09 '21 at 21:42
-
1Actually if you have CRSF turned on, you will get 403 with this configuration. So you need special filter created through requestMatcher().antMatcher(#same as in the post) and turn of CSRF protection or ignore the path on WebSecurity level as show in post above. Or you can try [Havelock](https://github.com/Majlanky/havelock) which is able to do exposure by one annotation. Disclaimer: I am the founder and tech lead of the project – Majlanky Apr 25 '22 at 12:52
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 SecurityConfig {
@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();
}
}
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.

- 143
- 2
- 10