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