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) }
}
}