@Test
@DisplayName("회원가입 요청보내기")
@WithAnonymousUser
void testSignup() throws Exception {
mockMvc.perform(post("/user/signup")
.with(SecurityMockMvcRequestPostProcessors.csrf()) // 이걸해야되네...
.param("username", "testuser")
.param("email", "test@example.com")
.param("password1", "password123")
.param("password2", "password123"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/"));
}
mockMvc를 이용해 회원가입 요청하는 controller에 대한 테스트를 하는도중 계속 오류가 발생했다.문제는 csrf였다.
CSRF 공격은 사용자가 의도하지 않은 요청을 악의적으로 서버에 전송하는 공격으로, 이를 방어하기 위해 서버는 각 요청에 대해 고유한 CSRF 토큰을 요구하고 이를 검증하는데 메인 프로젝트에서는 SpringSecurity설정파일에 csrf토큰에 대한 설정을 해주었지만 test에는 그런설정이 없어
with(SecurityMockMvcRequestPostProcessors.csrf())
이 코드를 통해서 csrf토큰을 추가해주어야 한다.