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>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <version>5.3.5.RELEASE / 5.4.1</version>
    <scope>test</scope>
</dependency>

Your unit test will require the following import to access it:

 import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)