此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.4.3spring-doc.cadn.net.cn

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

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

有许多选项可用于将用户关联到当前HttpServletRequest. 例如,以下将以用户(不需要存在)身份运行,用户名为 “user”、密码为 “password” 和角色 “ROLE_USER”:spring-doc.cadn.net.cn

支持的工作原理是将用户关联到HttpServletRequest. 要将请求关联到SecurityContextHolder您需要确保SecurityContextPersistenceFilterMockMvc实例。 有几种方法可以做到这一点:spring-doc.cadn.net.cn

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

您可以轻松进行自定义。 例如,以下将以用户(不需要存在)身份运行,用户名为 “admin”,密码为 “pass”,角色为 “ROLE_USER” 和 “ROLE_ADMIN”。spring-doc.cadn.net.cn

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

如果您有一个自定义的UserDetails,您也可以轻松指定。 例如,以下将使用指定的UserDetails(不需要存在)与UsernamePasswordAuthenticationToken的 Principal,其 Principal 为指定的UserDetails:spring-doc.cadn.net.cn

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

您可以使用以下方法以匿名用户身份运行:spring-doc.cadn.net.cn

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

如果您以默认用户身份运行并希望以匿名用户身份处理一些请求,这将特别有用。spring-doc.cadn.net.cn

如果您想要自定义Authentication(不需要存在)中,您可以使用以下命令执行此作:spring-doc.cadn.net.cn

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

您甚至可以自定义SecurityContext使用以下内容:spring-doc.cadn.net.cn

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

我们还可以通过使用MockMvcBuilders的默认请求。 例如,以下将以用户名称 “admin”、密码 “password” 和角色 “ROLE_ADMIN” 的用户(不需要存在)运行:spring-doc.cadn.net.cn

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

如果您发现在许多测试中使用相同的用户,建议将用户移动到某个方法。 例如,您可以在自己的名为CustomSecurityMockMvcRequestPostProcessors:spring-doc.cadn.net.cn

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

现在,您可以对CustomSecurityMockMvcRequestPostProcessors并在测试中使用它:spring-doc.cadn.net.cn

import static sample.CustomSecurityMockMvcRequestPostProcessors.*;

...

mvc
	.perform(get("/").with(rob()))
import sample.CustomSecurityMockMvcRequestPostProcessors.*

//...

mvc.get("/") {
    with(rob())
}

Running as a User in Spring MVC Test with Annotations

As an alternative to using a RequestPostProcessor to create your user, you can use annotations described in Testing Method Security. For example, the following will run the test with the user with username "user", password "password", and role "ROLE_USER":spring-doc.cadn.net.cn

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

Alternatively, the following will run the test with the user with username "user", password "password", and role "ROLE_ADMIN":spring-doc.cadn.net.cn

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