使用Spring的MockMVC测试API登录后,找不到x-auth-token标头

时间:2017-11-25 00:11:27

标签: spring-mvc spring-boot spring-security mockmvc spring-test-mvc

请考虑以下配置

Spring Boot应用程序:

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

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

网络安全配置:

@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
    }

以下测试代码:

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");

问题是token始终为空,我无法执行需要经过身份验证的会话的操作!

但是当我启动Spring Boot应用程序并使用REST客户端来模拟相同的登录操作时,我发现在HTTP响应头中返回了x-auth-token标头。

我应该如何使用测试API来接收x-auth-token

0 个答案:

没有答案