# 安全mckmvcresultmatchers
有时,希望对请求做出各种与安全相关的断言。为了满足这一需求, Spring 安全测试支持实现了 Spring MVC测试的ResultMatcher
接口。为了使用 Spring Security的ResultMatcher
实现,确保使用以下静态导入:
Java
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*;
Kotlin
import org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*
# 未经验证的断言
有时,断言没有经过身份验证的用户与MockMvc
调用的结果相关联可能是有价值的。例如,你可能想要测试提交的用户名和密码是否无效,并验证是否有用户通过了身份验证。使用 Spring Security的测试支持,你可以很容易地使用以下内容来实现这一点:
Java
mvc
.perform(formLogin().password("invalid"))
.andExpect(unauthenticated());
Kotlin
mvc
.perform(formLogin().password("invalid"))
.andExpect { unauthenticated() }
# 经过验证的断言
通常情况下,我们必须断言存在经过身份验证的用户。例如,我们可能想要验证我们的身份验证是否成功。我们可以使用以下代码片段来验证基于表单的登录是否成功:
Java
mvc
.perform(formLogin())
.andExpect(authenticated());
Kotlin
mvc
.perform(formLogin())
.andExpect { authenticated() }
如果我们想要确定用户的角色,我们可以改进以前的代码,如下所示:
Java
mvc
.perform(formLogin().user("admin"))
.andExpect(authenticated().withRoles("USER","ADMIN"));
Kotlin
mvc
.perform(formLogin())
.andExpect { authenticated().withRoles("USER","ADMIN") }
或者,我们可以验证用户名:
Java
mvc
.perform(formLogin().user("admin"))
.andExpect(authenticated().withUsername("admin"));
Kotlin
mvc
.perform(formLogin().user("admin"))
.andExpect { authenticated().withUsername("admin") }
我们也可以将这些断言结合起来:
Java
mvc
.perform(formLogin().user("admin"))
.andExpect(authenticated().withUsername("admin").withRoles("USER", "ADMIN"));
Kotlin
mvc
.perform(formLogin().user("admin"))
.andExpect { authenticated().withUsername("admin").withRoles("USER", "ADMIN") }
我们还可以对身份验证进行任意断言。
Java
mvc
.perform(formLogin())
.andExpect(authenticated().withAuthentication(auth ->
assertThat(auth).isInstanceOf(UsernamePasswordAuthenticationToken.class)));
Kotlin
mvc
.perform(formLogin())
.andExpect {
authenticated().withAuthentication { auth ->
assertThat(auth).isInstanceOf(UsernamePasswordAuthenticationToken::class.java) }
}
}