References:
- https://docs.spring.io/spring-security/site/docs/5.2.11.RELEASE/reference/html/test.html#test-mockmvc-smmrpp
- https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/csrf.html#csrf
To test your controllers without disabling CSRF, you can do the following:
1. First import statically the package bellow:
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
2. Then in your MockMvc request:
with(csrf())
3. And last:
this.mockMvc
.perform(post("/users").with(csrf())
.content(objectMapper.writeValueAsString(createUserDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isCreated());
The recomendation from Spring, says the following:
When should you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.