在 Spring MVC Test 中以用户身份运行一个测试

本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。

作为一个特定的用户运行测试往往是可取的。有两种简单的方法来填充用户。

用 RequestPostProcessor 在 Spring MVC Test 中以用户身份运行

你有许多选项可以将一个用户与当前的 HttpServletRequest 联系起来。下面的例子以一个用户(不需要存在)的身份运行,这个用户的用户名是 user,密码是 password,角色是 ROLE_USER

mvc
	.perform(get("/").with(user("user")))

该支持通过将用户与 HttpServletRequest 相关联来工作。为了将请求关联到 SecurityContextHolder,你需要确保 SecurityContextPersistenceFilterMockMvc 实例关联。你可以通过一些方式做到这一点。

  • 执行 apply(springSecurity())

  • 将 Spring Security 的 FilterChainProxy 添加到 MockMvc

  • 当使用 MockMvcBuilders.standaloneSetup 时,手动添加 SecurityContextPersistenceFilterMockMvc 实例可能是有意义的。

你可以很容易地进行定制。例如,以下内容将作为一个用户(不需要存在)运行,其用户名为 "admin",密码为 "pass",角色为 "ROLE_USER" 和 "ROLE_ADMIN"。

mvc
	.perform(get("/admin").with(user("admin").password("pass").roles("USER","ADMIN")))

如果你有一个你想使用的自定义 UserDetails,你也可以很容易地指定它。例如,下面将使用指定的 UserDetails(它不需要存在),以 UsernamePasswordAuthenticationToken 运行,该 UserDetails 有一个 principal。

mvc
	.perform(get("/").with(user(userDetails)))

你可以使用以下方法以匿名用户身份运行。

mvc
	.perform(get("/").with(anonymous()))

如果你用一个默认用户运行,并希望以匿名用户的身份处理一些请求,这就特别有用。

如果你想要一个自定义的 Authentication(不需要存在),你可以用下面的方法来做。

mvc
	.perform(get("/").with(authentication(authentication)))

你甚至可以用以下方法来定制 SecurityContext

mvc
	.perform(get("/").with(securityContext(securityContext)))

我们也可以通过使用 MockMvcBuilders 的默认请求来确保在每个请求中以特定的用户身份运行。例如,下面的内容将以一个用户(不需要存在)的身份运行,其用户名为 "admin",密码为 "password",角色为 "ROLE_ADMIN"。

mvc = MockMvcBuilders
		.webAppContextSetup(context)
		.defaultRequest(get("/").with(user("user").roles("ADMIN")))
		.apply(springSecurity())
		.build();

如果你发现你在许多测试中使用同一个用户,建议将用户移到一个方法中。例如,你可以在你自己的名为 CustomSecurityMockMvcRequestPostProcessors 的类中指定如下。

public static RequestPostProcessor rob() {
	return user("rob").roles("ADMIN");
}

现在你可以对 CustomSecurityMockMvcRequestPostProcessors 进行静态导入,并在你的测试中使用它。

import static sample.CustomSecurityMockMvcRequestPostProcessors.*;

...

mvc
	.perform(get("/").with(rob()))

在 Spring MVC Test 中以用户身份运行的注解

作为使用 RequestPostProcessor 来创建用户的替代方法,你可以使用 测试方法安全中 描述的注解。例如,下面将用用户名 "user"、密码 "password" 和角色 "ROLE_USER" 的用户运行测试。

@Test
@WithMockUser
public void requestProtectedUrlWithUser() throws Exception {
mvc
		.perform(get("/"))
		...
}

或者,下面将用用户名 "user"、密码 "password" 和角色 "ROLE_ADMIN" 的用户运行测试。

@Test
@WithMockUser(roles="ADMIN")
public void requestProtectedUrlWithUser() throws Exception {
mvc
		.perform(get("/"))
		...
}
主页