Unit testing controllers with CSRF protection enabled in Spring security
The way to solve this issue is : import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; … @Test public void testLogin() throws Exception { this.mockMvc.perform(post(“/login”) .param(“username”, “…”) .param(“password”, “…”) .with(csrf())) .andExpect(status().isFound()) .andExpect(header().string(“Location”, “redirect-url-on-success-login”)); } The important part is : .with(csrf()) which will add the expected _csrf parameter to the query. The csrf() static method is provided by spring-security-test : <dependency> … Read more