I am using Spring Boot 2.7.2 Security with following config for my open-api's swagger and other end points. I referred this and a lots of other related SO threads.
@Bean
@Order(1)
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
return http.build();
}
@Bean
@Order(2)
public SecurityFilterChain filterChainSwaggerUI(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/swagger-ui/**").permitAll();
return http.build();
}
I tried to combine them into one Bean and I tried without order as well. But every time I hit http://localhost:8080/swagger-ui/index.html
I see the login pop up in the browser. Which I dont want. I need the auth pop-up for my rest of the other end points only.
What I am doing wrong here?
CodePudding user response:
There is a difference between the antMatchers
in authorizeRequests
and antMatchers
for HttpSecurity
. If you change it to the following, it should work:
@Bean
@Order(1)
public SecurityFilterChain filterChainSwaggerUI(HttpSecurity http) throws Exception {
http.antMatcher("/swagger-ui/**").authorizeRequests().anyRequest().permitAll();
return http.build();
}
@Bean
@Order(2)
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
return http.build();
}
Notice that I used http.antMatcher
in the first bean.
With this configuration, you are saying that the first SecurityFilterChain
will only apply to requests that start with /swagger-ui
, and that every request that comes in is permitted. The second SecurityFilterChain
will apply to any other request. Remember that only one SecurityFilterChain
will be applied to the request.
You could also do it with one bean:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatcher("/swagger-ui/**").permitAll()
.anyRequest().authenticated().and()
.httpBasic();
return http.build();
}
There is a simple repository that configures Spring Security to allow requests to /swagger-ui/**
, you can run the SpringSecurityAllowSwaggerApplicationTests
tests to see the behavior. https://github.com/marcusdacoregio/spring-security-allow-swagger-url