Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebMvcTest: Migrating from WebSecurityConfigurerAdapter to SecurityFilterChain

As described here Spring Security deprecated WebSecurityConfigurerAdapter which I've been using for some time. I used the component based approach and introduced SecurityFilterChain and InMemoryUserDetailsManager beans (see: commit) but then one of my tests, which is using @WithMockUser failed.

Does @WebMvcTest tests work with @WithMockUser when using Spring Security component based approach (SecurityFilterChain)?

  • Tests: https://github.com/pszemus/spring-security-test/blob/master/src/test/java/com/example/springsecuritytest/TestControllerTest.java
  • Old security configuration that used WebSecurityConfigurerAdapter (for which all tests pass): https://github.com/pszemus/spring-security-test/blob/c323ce3af77bb067c7eef58fd933689ef97c082c/src/main/java/com/example/springsecuritytest/SecurityConfiguration.java
  • New security configuration that use component-based approach (givenMockedCredentials_shouldAccessSecuredEndpoint test fails with message: Status expected:<200> but was:<401>): https://github.com/pszemus/spring-security-test/blob/fb9b40194747a3b45678183276b81c582cb004a3/src/main/java/com/example/springsecuritytest/SecurityConfiguration.java

Whole project, with failing test, is located: https://github.com/pszemus/spring-security-test

like image 333
pszemus Avatar asked Oct 24 '25 16:10

pszemus


1 Answers

You should add @Import(YourSecurityConfiguration.class) in your test class. The @WebMvcTest is not picking up the configuration automatically, so you have to tell it explicitly which configuration to use.

like image 121
Marcus Hert da Coregio Avatar answered Oct 26 '25 23:10

Marcus Hert da Coregio