How to allow anonymous access to springdoc-openapi-ui (OpenAPI 3.0 /swagger-ui.html
) in a Spring Boot application secured by Spring Security?
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:
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With