I have a spring mvc (3.2.5) application with spring security (3.2).
I configured my SecurityConfig.class with this method :
@Override
protected void co
Post requests need the CSRF token to be added to the form. So you have to pass it while testing, code: ("it works on my machine" :))
String TOKEN_ATTR_NAME = "org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN";
// ...
HttpSessionCsrfTokenRepository httpSessionCsrfTokenRepository = new HttpSessionCsrfTokenRepository();
CsrfToken csrfToken = httpSessionCsrfTokenRepository.generateToken(new MockHttpServletRequest());
this.mockMvc.perform(
post("yourpath")
.sessionAttr(TOKEN_ATTR_NAME, csrfToken)
.param(csrfToken.getParamName(), csrfToken.getToken())...
2nd thing: are you sure that registration" method handles your post request? Isn't RequestMapping configured for "GET" by default? (I may be wrong here)
Try with @AutoConfigureMockMvc(addFilters = false)
I know this question is quite old, but this is one of the first results on Google for some queries and I believe this approach is much better and it is described on spring.io blog
1) You can create your mockMvc
with Spring Security support easier, so your setUp()
gets much shorter:
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.build();
}
2) You can use org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf()
to populate your test request with correct CSRF token like this:
mockMvc.perform(post("/register")
.with(csrf())
.param("action", "signup"))
.andExpect(status().isOk());