2

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)?

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

pszemus
  • 375
  • 2
  • 10
  • `I used the component based approach and introduced SecurityFilterChain and InMemoryUserDetailsManager` and where is that code, and where is you security debug logs that will tell you the reason for the 401? – Toerktumlare Jun 29 '22 at 13:15
  • 4
    Try adding `@Import(YourSecurityConfiguration.class)` in your test class – Marcus Hert da Coregio Jun 29 '22 at 13:49
  • 1
    @MarcusHertdaCoregio that was it! Thank you so much! If you post your advice as an answer, I'll make it an accepted one. – pszemus Jun 30 '22 at 06:56

1 Answers1

6

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.

  • I had the same problem, it would be nice include this information in the official link: https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter – doctore Nov 06 '22 at 13:05
  • This information is present in the testing section of Spring Boot https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto.testing.slice-tests – Marcus Hert da Coregio Nov 07 '22 at 11:18
  • Considering above link explains how to migrate Spring Security to work without WebSecurityConfigurerAdapter, makes sense to include how to adapt your tests too. Allowing to the people with a similar problem find the "whole solution" in only one location – doctore Nov 08 '22 at 22:14