Spring 启用安全性的 Boot 1.4 测试?

Spring Boot 1.4 testing with Security enabled?

我想知道我应该如何为我的测试验证用户身份?就目前而言,我将编写的所有测试都将失败,因为端点需要授权。

测试代码:

@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 安全性提供了一个 @WithMockUser 注释,可用于指示 test should be run as a particular user:

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

或者,如果您使用的是基本身份验证,则可以发送所需的 Authorization header:

@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());
}

因为它会生成相同的 header:

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