Question: Spring Security testing with CookieCsrfTokenRepository

Question

Spring Security testing with CookieCsrfTokenRepository

Answers 0
Added at 2016-12-20 12:12
Tags
Question

I created simple project in Spring Security and I'm trying to test my code. I use AngularJS as a frontend layer. My problem is related with CSRF. I get 403 http status when I'm trying test my controllers. Based on the documentation, I am under the impression that CSRF should have been configured, but that seems not to be the case. My configuration files:

In Security config:

http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())

In my base web test class I set up MockMvc with Security settings based on Spring documentation ( http://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/htmlsingle/#test-mockmvc-setup )

protected MockMvc buildMockMvcWithUserAuthentication() {
    return MockMvcBuilders.webAppContextSetup(wac)
            .apply(springSecurity())
            .build();
}

Now, In my test I have something like this:

@Test
public void postTest() throws Exception {
    message = Message.newInfoMessage(EXAMPLE_MESSAGE_CONTENT);

    String json = mapper.toJson(message);

    mvcWithAuthentication.perform(post(MessageController.MESSAGES_COLLECTION_URI)
            .with(csrf())
            .content(json)
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isCreated());

}

What I discovered, .with(csrf()) is using HttpSessionCsrfTokenRepository() object. My question is, if there is any simple way to use CookieCsrfTokenRepository in my JUnit test?

Answers
Source Show
◀ Wstecz