对于最新的稳定版本,请使用 Spring Security 6.3.1Spring中文文档

对于最新的稳定版本,请使用 Spring Security 6.3.1Spring中文文档

SecurityMockMvcResultMatchers

有时,需要对请求进行各种与安全相关的断言。 为了满足这一需求,Spring Security Test 支持实现了 Spring MVC Test 的接口。 为了使用 Spring Security 的实现,请确保使用以下静态导入:ResultMatcherResultMatcherSpring中文文档

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

未经身份验证的断言

有时,断言没有与调用结果关联的经过身份验证的用户可能很有价值。 例如,您可能希望测试提交无效的用户名和密码,并验证是否没有用户经过身份验证。 您可以使用如下所示的内容通过 Spring Security 的测试支持轻松执行此操作:MockMvcSpring中文文档

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

经过身份验证的断言

很多时候,我们必须断言存在经过身份验证的用户。 例如,我们可能希望验证我们是否成功进行了身份验证。 我们可以通过以下代码片段验证基于表单的登录是否成功:Spring中文文档

mvc
	.perform(formLogin())
	.andExpect(authenticated());
mvc
    .perform(formLogin())
    .andExpect { authenticated() }

如果我们想断言用户的角色,我们可以优化前面的代码,如下所示:Spring中文文档

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

或者,我们可以验证用户名:Spring中文文档

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

我们还可以组合这些断言:Spring中文文档

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

我们还可以对身份验证做出任意断言Spring中文文档

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