title: Spring Test for Controller Returns HTTP403 despite providing roles using @WithMockUser
body: <p>I am struggling with the setup of a Rest Controller test due to Spring Security.</p>
  <p>I am trying to test a basic rest endpoint:</p>
  <pre><code>@RestController
  @RequestMapping(value = &quot;/product&quot;)
  public class ProductInformationController {
  
    private final ProductInformationService productInformationService;
  
    ...
  
    @DeleteMapping(value = &quot;/{id}&quot;)
    public ResponseEntity&lt;Void&gt; deleteProductById(@PathVariable int id) {
      productInformationService.deleteProductById(id);
  
      return ResponseEntity.noContent().build();
    }
  </code></pre>
  <p>The basic smoke test looks as follows:</p>
  <pre><code>@ExtendWith(SpringExtension.class)
  @ContextConfiguration
  @WebMvcTest({ProductInformationController.class, CommonControllerAdvice.class})
  class ProductInformationControllerTest {
  
    private static final String SINGLE_RESOURCE_ENDPOINT_URL = &quot;/product/{id}&quot;;
  
    @Autowired
    MockMvc mockMvc;
  
    @MockBean
    ProductInformationService service;
  
    ...
  
    @Test
    @WithMockUser(roles={&quot;USER&quot;,&quot;ADMIN&quot;})
    void shouldReturn204ForDeleteProduct() throws Exception {
      var productId = 1;
      
      mockMvc.perform(delete(SINGLE_RESOURCE_ENDPOINT_URL, productId))
          .andExpect(status().isNoContent());
    }
  </code></pre>
  <p>I have Spring Security among the dependencies but the configuration that exposes the <code>SecurityFilterChain</code> as a <code>@Bean</code> is not among the classes that are loaded for this WebMvcTest.</p>
  <p>However, even despite having added both theoretically possible User Roles the test returns a HTTP 403 and does not even propagate the call to any handler:</p>
  <pre><code>MockHttpServletRequest:
        HTTP Method = DELETE
        Request URI = /product/1
         Parameters = {}
            Headers = []
               Body = null
      Session Attrs = {org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@7ba1cdbe, SPRING_SECURITY_CONTEXT=SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=user, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_ADMIN, ROLE_USER]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ROLE_ADMIN, ROLE_USER]]]}
  
  Handler:
               Type = null
  ...
  
  MockHttpServletResponse:
             Status = 403
      Error message = Forbidden
            Headers = [X-Content-Type-Options:&quot;nosniff&quot;, X-XSS-Protection:&quot;1; mode=block&quot;, Cache-Control:&quot;no-cache, no-store, max-age=0, must-revalidate&quot;, Pragma:&quot;no-cache&quot;, Expires:&quot;0&quot;, X-Frame-Options:&quot;DENY&quot;]
       Content type = null
               Body = 
      Forwarded URL = null
     Redirected URL = null
            Cookies = []
  </code></pre>
  <p>Manual tests of the endpoint work as expected. Any tests using GET work as expected as well, other HTTP verbs run into the same issue.</p>
  <p>I assume the issue is the partial setup of Spring Security here. Since I only want to test the Controller I don't want to include the entire Spring Security configuration.</p>
  <p>How can I make this controller test work with the most minimal set of other classes and a most lean application context?</p>