跳到主要内容

SecurityMockMvcResultMatchers

QWen Max 中英对照 Security ResultMatchers SecurityMockMvcResultMatchers

有时,需要对请求做出各种与安全相关的断言。为了满足这一需求,Spring Security 测试支持实现了 Spring MVC 测试的 ResultMatcher 接口。为了使用 Spring Security 的 ResultMatcher 实现,请确保使用以下静态导入:

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

未经身份验证的断言

有时,断言 MockMvc 调用的结果中没有经过身份验证的用户可能是有价值的。例如,您可能希望测试提交无效的用户名和密码,并验证没有用户被认证。您可以使用 Spring Security 的测试支持轻松地做到这一点,如下所示:

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

认证断言

我们经常需要断言一个已认证的用户存在。例如,我们可能想要验证我们是否成功认证。我们可以使用以下代码片段来验证基于表单的登录是否成功:

mvc
.perform(formLogin())
.andExpect(authenticated());
java

如果我们想断言用户的角色,可以将之前的代码优化如下:

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

或者,我们可以验证用户名:

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

我们也可以组合断言:

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)));
java