Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable security in springBootTest using WebTestClient

SpringBoot in 2.1 Release Notes contain the following piece of information:

Security configuration is now applied to WebTestClient. For more information on testing secured endpoints, please refer to the relevant section of Spring Security’s reference documentation.

Problem:

After updating SpringBoot from 2.0.4 to 2.1.2 I found that my tests have stopped to work. I am using @SpringBootTest for my REST test. My WebTestClient cannot reach server. I did try a lot (e.g. from here) to mock or disable security and still getting 403 FORBIDDEN response.

Do you have any clues what can be wrong?

I create WebTestClient in the following way:

client = WebTestClient
  .bindToServer()
  .baseUrl("http://localhost:$port")
  .build()

Also tried to exclude SecurityAutoConfiguration.class.

like image 916
naitsabes Avatar asked Jan 30 '19 14:01

naitsabes


People also ask

How do I disable Spring Security for unit testing?

One of the ways you can disable Spring Security filters in your tests, is to use the @AutoConfigureMockMvc annotation. @AutoConfigureMockMvc annotation can be applied to a test class to enable and configure auto-configuration of MockMvc.

How do I disable spring boot security?

enabled=false and management. security. enabled=false should be set to disable the security.

How do I manage security in spring boot?

For adding a Spring Boot Security to your Spring Boot application, we need to add the Spring Boot Starter Security dependency in our build configuration file. Maven users can add the following dependency in the pom. xml file. Gradle users can add the following dependency in the build.


1 Answers

In some dark place, deep down the rabbit hole I found this:

@TestConfiguration
@Order(1)
public class SecurityConfiguration
  implements WebSecurityConfigurer<WebSecurity> {

  @Override
  public void init(WebSecurity builder) throws Exception {
    builder.ignoring().requestMatchers(
      new AntPathRequestMatcher("/**"));
  }

  @Override
  public void configure(WebSecurity builder) throws Exception {
  }

}

Remember to register class in @SpringBootTest, for instance:

@SpringBootTest(
  classes = [SomeApplication, SecurityConfiguration],
  webEnvironment = RANDOM_PORT
)

It's not disabling spring security, but it makes it transparent.

like image 78
Maciek Murawski Avatar answered Sep 17 '22 16:09

Maciek Murawski