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

Lit*_*cas 12 spring spring-mvc spring-security spring-test-mvc spring-boot

我想知道如何为我的测试验证用户身份?现在,我将编写的所有测试都将失败,因为端点需要授权.

测试代码:

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


}
Run Code Online (Sandbox Code Playgroud)

我找到的一个解决方案是通过在@WebMvcTest中将secure设置为false来禁用它.但这不是我想要做的.

有任何想法吗?

And*_*son 26

Spring Security提供了一个@WithMockUser注释,可用于指示测试应作为特定用户运行:

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

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

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

  • 注释包含在_spring-security-test_中.只需将依赖项_org.springframework.security:spring-security-test_添加到您的项目中即可 (11认同)
  • Spring Security甚至内置了对[Testing HTTP Basic Authentication]的支持(http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#testing-http-basic-authentication).;) (6认同)

Pav*_*lov 7

作为上一个答案的替代方案,可以使用以下内容:

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

因为它将生成相同的标题:

Headers = [Content-Type:"...", Authorization:"Basic dXNlcjpzZWNyZXQ="]
Run Code Online (Sandbox Code Playgroud)