|
对于最新的稳定版本,请使用 Spring Security 7.0.4! |
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) }
}
}