programing

보안이 활성화된 상태에서 Spring Boot 1.4 테스트를 수행하시겠습니까?

muds 2023. 7. 15. 10:42
반응형

보안이 활성화된 상태에서 Spring Boot 1.4 테스트를 수행하시겠습니까?

테스트를 위해 사용자를 인증하려면 어떻게 해야 하는지 궁금합니다.현재 상태로는 엔드포인트에 승인이 필요하기 때문에 작성할 모든 테스트가 실패합니다.

테스트 코드:

@RunWith(SpringRunner.class)
@WebMvcTest(value = PostController.class)
public class PostControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private PostService postService;

    @Test
    public void testHome() throws Exception {
        this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("posts"));
    }


}

제가 찾은 한 가지 해결책은 @WebMvcTest에서 secure를 false로 설정하여 비활성화하는 것입니다.하지만 그것은 제가 하려는 것이 아닙니다.

아이디어 있어요?

Spring Security는 다음을 제공합니다.@WithMockUser특정 사용자로 테스트를 실행해야 함을 나타내는 데 사용할 수 있는 주석:

@Test
@WithMockUser(username = "test", password = "test", roles = "USER")
public void withMockUser() throws Exception {
    this.mockMvc.perform(get("/")).andExpect(status().isOk());
}

또는 기본 인증을 사용하는 경우 필요한 정보를 전송할 수 있습니다.Authorization머리글:

@Test
public void basicAuth() throws Exception {
    this.mockMvc
            .perform(get("/").header(HttpHeaders.AUTHORIZATION,
                    "Basic " + Base64Utils.encodeToString("user:secret".getBytes())))
            .andExpect(status().isOk());
}

이전 답변에 대한 대안으로 다음을 사용할 수 있습니다.

@Test
public void basicAuth() throws Exception {
    this.mockMvc
            .perform(get("/")
                .with(SecurityMockMvcRequestPostProcessors.httpBasic("user", "secret"))
            )
            .andExpect(status().isOk());
}

동일한 헤더를 생성하므로:

Headers = [Content-Type:"...", Authorization:"Basic dXNlcjpzZWNyZXQ="]

언급URL : https://stackoverflow.com/questions/37817599/spring-boot-1-4-testing-with-security-enabled

반응형