lundi 27 juin 2016

How to access a CSRF token in a Spring controller unit test?

I have a Spring controller that upon an authenticated GET from "/user" returns the following JSON:

{"name":<name>,"token":<csrf-token>}

I tried to construct a unit test for the controller that will verify that the returned JSON contains a dynamically-generated CSRF token:

@Autowired
private FilterChainProxy springSecurityFilterChain;

private MockMvc mvc;

@Before
public void setUp()
    throws Exception
{
    ...
    mvc = standaloneSetup(controller)
        .apply(springSecurity(springSecurityFilterChain))
        .build();
}

@Test
public void getUser()
    throws Exception
{
    CsrfRequestPostProcessor csrfPostProcessor = null;
    mvc.perform(get("/user").with(user(Const.USER)).with(csrfPostProcessor = csrf()))
        .andExpect(status().isOk())
        .andExpect(content().json("{\"name\":\"" + Const.NAME + "\",\"token\":\"" + csrfPostProcessor.toString() + "\"}"));
}

The test fails along these lines:

Failed tests: 
  ControllerTest.getUser:74 token
Expected: org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$CsrfRequestPostProcessor@203c20cf
     got: 565a95b0-d0bb-4376-a8a0-725a3b16a787

As you can see, in json() the csrfPostProcessor.toString() returns the actual token, but somehow when the test is constructed an Object-like toString() is used to build the JSON template.

Is there any way to fix this and if not, is there a way to construct an alternative test that will use a dynamically-generated CSRF token?

Aucun commentaire:

Enregistrer un commentaire