Expected behaviour
Beans of type WebSecurityCustomizer are created during test execution when using @WebMvcTest.
Context
In Spring Security there are two ways to customize WebSecurity.
1st - use WebSecurityConfigurer, which was previously implemented by already deprecated and removed WebSecurityConfigurerAdapter.
2nd - since Spring Security 5.4 we can use WebSecurityCustomizer instead of WebSecurityConfigurerAdapter.
Beans of type WebSecurityCustomizer are used by WebSecurityConfiguration to execute actual customization.
When I use @WebMvcTest I want my custom WebSecurityCustomizer to be picked up by the framework automatically during test execution.
However, since WebMvcTypeExcludeFilter doesn't include such beans - they are ignored/filtered out:
https://github.com/spring-projects/spring-boot/blob/4be3dc22625456334f6643eeeebc50cc9eda03ea/module/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTypeExcludeFilter.java#L54-L56
Should beans of type WebSecurityCustomizer be included in the OPTIONAL_INCLUDES array similar to WebSecurityConfigurer?
Comment From: ahrytsiuk
I've created a small example https://github.com/ahrytsiuk/spring-boot-gh47255. It's a bit artificial, but I hope I can demonstrate the point well.
If you run tests you can see that FavIconWebMvcTest fails, but if I import WebSecurityCustomizer configuration explicitly - the test passes (see FavIconWebMvcFixedTest).
Comment From: SeoHyeok2
I'd like to work on this issue. Could you please assign it to me?
Comment From: philwebb
Thanks @SeoHyeok2, I've assigned the issue to you.
Comment From: Oma3r3
I would like to work on this issue if you could assign it to me.
Comment From: wilkinsona
Thanks, @Oma3r3, but @SeoHyeok2 has already offered to work on this and the issue is assigned to them.
Comment From: SeoHyeok2
Hello, I've been debugging this issue further and have some new findings.
- I created a failing test (
WebMvcTestWithWebSecurityCustomizerIntegrationTests) as per the TDD process. - My first attempt was to add
WebSecurityCustomizertoOPTIONAL_INCLUDESinWebMvcTypeExcludeFilter. - This resulted in a
404 Not Founderror in my test, indicating theTestControllerwas no longer being picked up. - Debugging showed that when
controllersare specified in@WebMvcTest, thegetDefaultIncludes()method returns a set that does not includeController.class, which seems to be the cause of the 404. - My attempts to fix this by modifying
getDefaultIncludes()orgetComponentIncludes()caused many other existing tests (likeWebMvcTestNestedIntegrationTests) to fail, as it seems to break the controller filtering logic.
It seems a simple one-line fix has too many side effects. Could you provide some guidance on the correct way to modify WebMvcTypeExcludeFilter to include WebSecurityCustomizer without breaking the existing controller scanning behavior? Any help would be greatly appreciated.