servlet-test-mockmvc-authentication.md 5.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
# 在 Spring MVC测试中以用户身份运行测试

通常希望以特定用户的身份运行测试。有两种简单的填充用户的方法:

* [在使用RequestPostProcessor的 Spring MVC测试中以用户身份运行](#test-mockmvc-securitycontextholder-rpp)

* [在 Spring MVC测试中以用户身份运行并带有注释](#test-mockmvc-withmockuser)

## Running as a User in Spring MVC Test with RequestPostProcessor

有许多选项可用于将用户关联到当前的`HttpServletRequest`。例如,以下将以用户名“user”、密码“password”和角色“role\_user”作为用户(不需要存在)运行:

|   |该支持通过将用户关联到`HttpServletRequest`来工作。<br/>将请求关联到你需要确保的`SecurityContextHolder``SecurityContextPersistenceFilter``MockMvc`实例相关联。<br/>实现此目的的几种方法是:<br/><br/>*调用[`apply(springSecurity())`<br/><br/>*将 Spring 安全性的`FilterChainProxy`添加到<32">r=R=”42“/>”43“/>r=”gt=34"实例可能具有意义使用`MockMvcBuilders.standaloneSetup`时|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Java

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

Kotlin

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

你可以轻松地进行自定义。例如,以下内容将以用户名“admin”、密码“pass”以及角色“role\_user”和“role\_admin”的形式(不需要存在)运行。

Java

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

Kotlin

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

如果你有一个想要使用的自定义`UserDetails`,那么你也可以轻松地指定它。例如,下面将使用指定的`UserDetails`(不需要存在)来运行具有指定的`UsernamePasswordAuthenticationToken`的主体的`UserDetails`:

Java

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

Kotlin

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

你可以使用以下方式以匿名用户的身份运行:

Java

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

Kotlin

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

如果你运行的是一个默认用户,并且希望以匿名用户的身份处理一些请求,那么这一点尤其有用。

如果你想要自定义`Authentication`(它不需要存在),可以使用以下方法来实现:

Java

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

Kotlin

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

你甚至可以使用以下方法自定义`SecurityContext`:

Java

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

Kotlin

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

通过使用`MockMvcBuilders`的默认请求,我们还可以确保每个请求都以特定用户的身份运行。例如,以下内容将以用户名“admin”、密码“password”和角色“role\_admin”的用户身份(不需要存在)运行:

Java

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

Kotlin

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

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

Java

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

Kotlin

```
fun rob(): RequestPostProcessor {
    return user("rob").roles("ADMIN")
}
```

现在,你可以在`CustomSecurityMockMvcRequestPostProcessors`上执行静态导入,并在测试中使用它:

Java

```
import static sample.CustomSecurityMockMvcRequestPostProcessors.*;

...

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

Kotlin

```
import sample.CustomSecurityMockMvcRequestPostProcessors.*

//...

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

## Running as a User in Spring MVC Test with Annotations

作为使用`RequestPostProcessor`创建用户的替代方法,你可以使用[测试方法安全性](../method.html)中描述的注释。例如,下面将使用用户名“user”、密码“password”和角色“role\_user”对用户运行测试:

Java

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

Kotlin

```
@Test
@WithMockUser
fun requestProtectedUrlWithUser() {
    mvc
        .get("/")
        // ...
}
```

或者,下面将使用用户名“user”、密码“password”和角色“role\_admin”对用户运行测试:

Java

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

Kotlin

```
@Test
@WithMockUser(roles = ["ADMIN"])
fun requestProtectedUrlWithUser() {
    mvc
        .get("/")
        // ...
}
```

[安全请求后置处理器](request-post-processors.html)[嘲笑CSRF](csrf.html)