Spring mvc 使用Spring';登录后未找到x-auth-token头;MockMVC测试API 请考虑以下配置
Spring启动应用程序:Spring mvc 使用Spring';登录后未找到x-auth-token头;MockMVC测试API 请考虑以下配置,spring-mvc,spring-boot,spring-security,mockmvc,spring-test-mvc,Spring Mvc,Spring Boot,Spring Security,Mockmvc,Spring Test Mvc,Spring启动应用程序: @SpringBootApplication @EnableRedissonHttpSession @ComponentScan(basePackages = { "com.ja.pi" }) public class PiApp { @Bean public HttpSessionStrategy httpSessionStrategy() { return new HeaderHttpSessionStrategy();
@SpringBootApplication
@EnableRedissonHttpSession
@ComponentScan(basePackages = { "com.ja.pi" })
public class PiApp {
@Bean
public HttpSessionStrategy httpSessionStrategy() {
return new HeaderHttpSessionStrategy();
}
Web安全配置:
@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");
问题是令牌
始终为空,我无法执行需要经过身份验证的会话的操作
但是,当我启动Spring启动应用程序并使用REST客户端模拟相同的登录操作时,我发现HTTP响应头中返回了x-auth-token
头
我应该如何处理测试API以允许接收
x-auth-token
?起初,我是这样创建web应用程序上下文的
mockMvc = webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
但解决方案是获取SessionRepositoryFilter的实例并将其添加到web应用程序上下文中。过滤器负责返回x-auth-token
头
SessionRepositoryFilter<?> filter = webApplicationContext.getBean(SessionRepositoryFilter.class);
mockMvc = webAppContextSetup(webApplicationContext).addFilters(filter).apply(springSecurity()).build();
SessionRepositoryFilter=webApplicationContext.getBean(SessionRepositoryFilter.class);
mockMvc=webAppContextSetup(webApplicationContext).addFilters(filter).apply(springSecurity()).build();
您能展示一下如何获得MockMvc实例吗?您使用的是哪个版本的Spring Boot?我没有将SessionRepositoryFilter
过滤器添加到创建的web应用程序上下文中。我发布了一个解决方案。我不知道我还缺少什么。我尝试了几种选择,但我仍在为每个请求获取新的x-auth-token(新会话)。我恐怕目前对此无能为力。