SecurityMockMvcResultMatchers

有時,我們希望針對請求進行各種與安全性相關的斷言。為了滿足此需求,Spring Security Test 支援實作了 Spring MVC Test 的 ResultMatcher 介面。為了使用 Spring Security 的 ResultMatcher 實作,請確保使用以下靜態匯入:

  • Java

  • Kotlin

import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*;
import org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*

未經驗證的斷言

有時,斷言結果中沒有與 MockMvc 調用相關聯的已驗證使用者可能很有價值。例如,您可能想要測試提交無效的使用者名稱和密碼,並驗證沒有使用者通過身份驗證。您可以使用 Spring Security 的測試支援輕鬆地做到這一點,如下所示:

  • Java

  • Kotlin

mvc
	.perform(formLogin().password("invalid"))
	.andExpect(unauthenticated());
mvc
    .perform(formLogin().password("invalid"))
    .andExpect { unauthenticated() }

已驗證的斷言

通常,我們必須斷言已驗證使用者存在。例如,我們可能想要驗證我們是否成功通過身份驗證。我們可以透過以下程式碼片段驗證基於表單的登入是否成功:

  • Java

  • Kotlin

mvc
	.perform(formLogin())
	.andExpect(authenticated());
mvc
    .perform(formLogin())
    .andExpect { authenticated() }

如果我們想要斷言使用者的角色,我們可以如下所示精進先前的程式碼:

  • Java

  • Kotlin

mvc
	.perform(formLogin().user("admin"))
	.andExpect(authenticated().withRoles("USER","ADMIN"));
mvc
    .perform(formLogin())
    .andExpect { authenticated().withRoles("USER","ADMIN") }

或者,我們可以驗證使用者名稱:

  • Java

  • Kotlin

mvc
	.perform(formLogin().user("admin"))
	.andExpect(authenticated().withUsername("admin"));
mvc
    .perform(formLogin().user("admin"))
    .andExpect { authenticated().withUsername("admin") }

我們也可以組合這些斷言:

  • Java

  • Kotlin

mvc
	.perform(formLogin().user("admin"))
	.andExpect(authenticated().withUsername("admin").withRoles("USER", "ADMIN"));
mvc
    .perform(formLogin().user("admin"))
    .andExpect { authenticated().withUsername("admin").withRoles("USER", "ADMIN") }

我們也可以對身份驗證進行任意斷言:

  • Java

  • Kotlin

mvc
	.perform(formLogin())
	.andExpect(authenticated().withAuthentication(auth ->
		assertThat(auth).isInstanceOf(UsernamePasswordAuthenticationToken.class)));
mvc
    .perform(formLogin())
    .andExpect {
        authenticated().withAuthentication { auth ->
            assertThat(auth).isInstanceOf(UsernamePasswordAuthenticationToken::class.java) }
        }
    }