簡體   English   中英

MockMVC formLogin身份驗證…和業務操作

[英]MockMVC formLogin authentication… and business actions

此測試無法正常工作:POST請求未通過身份驗證

@Test public void testSecuredPostEntity() throws Exception { mockMvc.perform(formLogin().user("test").password("test")) .andExpect(authenticated().withUsername("test").withRoles("ADMIN")); mockMvc.perform(post("/authors") .content("{\\"name\\":\\"toto\\",\\"birth\\":\\"2016-01-01\\"}") .contentType(MediaType.APPLICATION_JSON)) .andExpect(authenticated()) // FAILURE no authentication .andExpect(status().isOk()) // 403 here if above commented .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.id", notNullValue())) .andExpect(jsonPath("$.createdBy", is("test"))) .andExpect(jsonPath("$.createdDate", notNullValue())); mockMvc.perform(logout()) .andExpect(status().isOk()); }

請問有人知道執行此請求時如何保持身份驗證嗎?

好的,我知道了:

    MvcResult mvcResult = mockMvc.perform(formLogin().user("test").password("test"))
            .andExpect(authenticated().withUsername("test")
                                      .withRoles("ADMIN"))
            .andReturn();
    MockHttpSession session = (MockHttpSession) mvcResult.getRequest().getSession(false);

    mockMvc.perform(post("/authors")
            .session(session)
            .content("{\"name\":\"toto\",\"birth\":\"2016-01-01\"}")
            .contentType(MediaType.APPLICATION_JSON));

根據您的評論答復,您似乎沒有對MockMvcBuilders應用任何特殊的東西,因此我假設您使用的是standaloneSetup或webAppContextSetup,而沒有其他選擇。

為了進行安全意識的集成測試,您首先應該在webAppContextSetup上啟用springSecurity()(AFAIK僅適用於此設置),如下所示:

mockMvc = MockMvcBuilders.webAppContextSetup(context)
            .apply(springSecurity())
            .build();

這將再次打開安全性(對於正常的集成測試,安全性已關閉)。

現在,您只需使用@WithMockUser批注即可啟用自定義用戶身份驗證:

@Test
@WithMockUser(username = "test", roles = {"ADMIN"})
public void testSecuredPostEntity() throws Exception {
    mockMvc.perform(post("/authors")
                .content("{\"name\":\"toto\",\"birth\":\"2016-01-01\"}")
                .contentType(MediaType.APPLICATION_JSON))
            .andExpect(authenticated()) // FAILURE no authentication
            .andExpect(status().isOk()) // 403 here if above commented
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$.id", notNullValue()))
            .andExpect(jsonPath("$.createdBy", is("test")))
            .andExpect(jsonPath("$.createdDate", notNullValue()));
}

注意:這些功能需要org.springframework.security:spring-security-test依賴項

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM