使用junit测试需要csrf令牌的请求,核心做法是在测试环境中关闭csrf保护或手动注入有效令牌。spring security默认在web应用中启用csrf防护,但在单元测试中可以通过配置禁用该过滤器,或者通过`mockmvc`的`csrf()`方法模拟携带合法令牌的行为。这样既能验证业务逻辑,又能确保安全机制在集成测试中正常工作。

如何在MockMvc中模拟携带CSRF令牌
在单元测试中使用`MockMvc`时,可以通过调用`.csrf()`方法来自动获取并注入一个有效的CSRF令牌到请求中。这种方法适用于需要验证CSRF拦截器是否生效的场景。具体做法是构建一个`RequestPostProcessor`,它会在发送请求前从`CsrfTokenRepository`获取令牌,并将其添加到请求参数或Header中。这样模拟了真实浏览器行为,确保后端能正确解析和验证令牌。

import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@Configuration
class TestConfig {
@Bean
CsrfTokenRepository csrfTokenRepository() {
return new HttpSessionCsrfTokenRepository();
}
}
@WebMvcTest(controllers = MyController.class)
@WithMockUser
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testWithCsrf() throws Exception {
mockMvc.perform(post("/submit")
.with(csrf())) // 关键:自动注入CSRF令牌
.andExpect(status().isOk());
}
}
上述代码展示了如何在一个标准的Spring Boot Web MVC测试中启用CSRF支持。通过引入`spring-security-test`依赖,可以使用静态导入的`csrf()`方法。该方法会查询当前会话中的`CsrfToken`,如果不存在则生成一个新的,并将其作为隐藏字段或Header附加到请求中。这确保了测试能够顺利通过CSRF检查,同时保持了对安全机制的验证。
如何完全禁用测试环境中的CSRF保护
如果测试目标是验证业务逻辑而非安全机制,或者希望简化测试设置,可以选择在测试配置中完全禁用CSRF保护。这通常通过在`WebSecurityConfigurerAdapter`或新的`SecurityFilterChain`配置中调用`.csrf().disable()`来实现。这种方式下,所有POST、PUT等状态改变请求都不再需要携带令牌,从而避免了令牌管理带来的复杂性。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class TestSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // 禁用CSRF
.authorizeHttpRequests(auth -> auth
.anyRequest().permitAll()
);
return http.build();
}
}
这种配置方式适用于纯单元测试或集成测试中不需要验证CSRF场景的情况。通过显式禁用CSRF,开发者可以专注于测试控制器逻辑、数据绑定和异常处理,而不必担心因缺少令牌导致的403错误。需要注意的是,这种配置仅应用于测试环境,生产环境应始终保持CSRF开启以保障应用安全。
当CSRF令牌无效或过期时测试框架如何处理
当测试中提供的CSRF令牌无效、缺失或已过期时,Spring Security会抛出`InvalidCsrfTokenException`或返回HTTP 403 Forbidden状态码。在`MockMvc`测试中,如果未正确注入令牌或故意提供错误令牌,请求将被拦截,导致测试失败。这种行为符合预期,因为它模拟了真实攻击场景下的防御机制。开发者可以通过捕获异常或检查响应状态来验证这一行为。











