Unit testing controllers with CSRF protection enabled in Spring security

uiroshan picture uiroshan · Sep 1, 2014 · Viewed 11.2k times · Source

Recently we have introduced CSRF protection for our project which uses spring security 3.2.

After enabling CSRF some of the unit tests are failing because of the csrf token is not present in request. I put some dummy value into '_csrf' parameter and it didn't work.

Is there anyway that I can get the csrf token before sending the request (when unit testing)?

Answer

Thierry picture Thierry · Jul 10, 2015

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.*;