Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty response headers from Spring MockMvc with springSecurityFilterChain

I write unit tests for my Spring MVC application.

This is my mockMvc initialization code:

@Configuration
public class SpringMockFactory {
    @Autowired
    private WebApplicationContext wac;

    @Autowired
    private FilterChainProxy springSecurityFilterChain;

    @Bean
    @Scope("prototype")
    public MockMvc getMockMvc() {
        return webAppContextSetup(wac)
                .addFilter(springSecurityFilterChain)
                .build();
    }
}

Everything works good, but when I add springSecurityFilterChain response headers are always empty (it's important cause I want to check Set-Cookie header).

I use this code to perform action:

resultActions = mockMvc.perform(post("/api/login")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("username", "sysadmin")
                .param("password", "password")
).andDo(print());

And this is the result of andDo(print()):

MockHttpServletResponse:
          Status = 200
   Error message = null
         Headers = {}
    Content type = null
            Body = {"status":200}
   Forwarded URL = null
  Redirected URL = null
         Cookies = []

The question is why are the response headers empty when I use springSecurityFilterChain with mockMvc? And how to read them?

like image 388
Vitalii Ivanov Avatar asked Nov 01 '22 15:11

Vitalii Ivanov


1 Answers

You may need to add Spring security configuration to your MockMvc object.

Example:

mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();

The springSecurity() initializer is available in org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers package. You can conveniently static import it. Note that you need org.springframework.security:spring-security-test dependency (I was good with 4.0.1.RELEASE).

See an example here (didactic project).

I didn't need to manually set a Spring Security filter chain.

like image 93
Marco Ferrari Avatar answered Nov 08 '22 08:11

Marco Ferrari