The secure flag dictates if Spring Security's mock mvc support should be auto-configured when it is
on the classpath. It also imports SecurityAutoConfiguration
if set to true. However, Spring Security provides some handy test support which means you do not need to disable security for tests in most cases. For example, you can add @WithMockuser
and the test will run with an authenticated user.
This will also cause this bug to go away.
Comment From: serac
While I can appreciate the intention to use an existing facility for mocking security, I think there's a legitimate use case for disabling security altogether for testing controllers that don't have any security constraints. It's fairly common to pull in service-layer components to the security configuration, and for controllers that are outside the Spring Security filter chain that results in a lot of unrelated configuration required to simply satisfy dependencies that would otherwise not be required. secure=false
is a simple solution; unfortunately I've not found an equivalent solution to disable Spring Security auto-configuration.
Please let me know if I should raise this concern in a more appropriate forum.
Comment From: wilkinsona
When you are testing a controller that should not have any security constraints, do you not want the tests to verify that they have no security constraints? secure=false
may have been simple, but it brought with it a risk of buggy security configuration going undetected.
Comment From: serac
@wilkinsona You make a fair point for simples cases like a site that has a public landing page but everything else requires authentication. You presumably want the public view to flex the isAuthenticatedAnonymously
constraint. Thinking about it more conceptually, though, I have controllers that are semantically outside Spring Security and I simply want to disable security altogether. Unfortunately the implementation of SS on top of the servlet spec and filters gets in the way and the filter chain runs whether I want it to or not. If there were a lower-level flag that I could toggle to get this behavior, that would be fine, but I'm not aware of any such capability.
Comment From: gavenkoa
I'm using
@WebAppConfiguration
@Import({MockMvcAutoConfiguration.class})
@EnableConfigurationProperties({ResourceProperties.class, WebMvcProperties.class})
instead of @WebMvcTest
to avoid Spring Security filters.
Comment From: varun-vivek
@gavenkoa could you please share any sample code of your test im gettin 401 but expected result should be 200 Thanks in advance !!!!!!!!