Search code examples
spring-mvcspring-bootspring-securitymockmvcspring-test-mvc

No x-auth-token header is found after logging in using Spring's MockMVC test API


Please consider the following configuration

Spring Boot application:

@SpringBootApplication
@EnableRedissonHttpSession
@ComponentScan(basePackages = { "com.ja.pi" })
public class PiApp {

    @Bean
    public HttpSessionStrategy httpSessionStrategy() {
        return new HeaderHttpSessionStrategy();
    }

Web security configuration:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserHandler userHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        //@formatter:off
            .anonymous().disable() // Disable anonymous sessions
            .csrf().disable()
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .successHandler(getLoginSuccessHandler())
                .failureHandler(getLoginFailureHandler())
                .loginPage("/login")
                .usernameParameter("email")
                .permitAll()
                .and()
            .logout()
                .logoutUrl("/user/logout");
      //@formatter:on
    }

And the following test code:

MockHttpServletRequestBuilder requestBuilder = post("/login").contentType("application/x-www-form-urlencoded").param("email", user.getEmail()).param("password", user.getPassword());

ResultActions result = mockMvc.perform(requestBuilder).andExpect(status().isOk());

MockHttpServletResponse response = result.andReturn().getResponse();
String token = response.getHeader("x-auth-token");

The problem is that token is always null and I can't perform actions that require an authenticated session!

But when I startup the Spring Boot application and use a REST client to simulate the same action of login, I find the x-auth-token header returned back in the HTTP response headers.

What should I do with the test API to allow receiving the x-auth-token ?


Solution

  • At first, I was creating the web-app context this way

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

    But the solution is to obtain an instance of the SessionRepositoryFilter filter and add it to the web-app context. The filter is responsible for returning the x-auth-token header.

    SessionRepositoryFilter<?> filter = webApplicationContext.getBean(SessionRepositoryFilter.class);
    mockMvc = webAppContextSetup(webApplicationContext).addFilters(filter).apply(springSecurity()).build();