'Spring Boot MockMvc Authentication Object Is Null

@DeleteMapping("/uri/{id}")
public ResponseEntity<RestResponseBody> delete(@PathVariable Long id, Authentication auth) {
     return ResponseEntity.ok(new RestResponseBody());
}

This is the controller, and the Authentication object is null when I use MockMvc. But, SecurityContextHolder.getContext().getAuthentication() is not null. I can get the authentication information from SecurityContextHolder, but not from the Authentication parameter.

Note: While not using the MockMvc, there is no problem.

@SpringBootTest(classes = TestApplication.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
@AutoConfigureMockMvc(addFilters = false)
public class XTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @Transactional
    @WithMyUser
    void deleteTest() throws Exception {

        MyUser principal = (MyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.delete("/uri/{id}", 00000)
                                                   .with(authentication(SecurityContextHolder.getContext().getAuthentication()))
                                                                 .contentType(MediaType.APPLICATION_JSON)
                                                                 .accept(MediaType.APPLICATION_JSON)).andReturn();

        System.out.println(result);
    }
}

The principal in the test class is not null. But when I send the request to the controller, the authentication parameter becomes null even if SecurityContextHolder is not null. What I am missing here?



Solution 1:[1]

https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/test-mockmvc.html#test-mockmvc-setup

In order to use Spring Security with Spring MVC Test it is necessary to add the Spring Security FilterChainProxy as a Filter. It is also necessary to add Spring Security’s TestSecurityContextHolderPostProcessor to support Running as a User in Spring MVC Test with Annotations. This can be done using Spring Security’s SecurityMockMvcConfigurers.springSecurity()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 xiaobo9