servlet-test-mockmvc-authentication.md 5.9 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
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 238 239 240 241 242 243 244
# Running a Test as a User in Spring MVC Test

It is often desirable to run tests as a specific user.
There are two simple ways of populating the user:

* [Running as a User in Spring MVC Test with RequestPostProcessor](#test-mockmvc-securitycontextholder-rpp)

* [Running as a User in Spring MVC Test with Annotations](#test-mockmvc-withmockuser)

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

There are a number of options available to associate a user to the current `HttpServletRequest`.
For example, the following will run as a user (which does not need to exist) with the username "user", the password "password", and the role "ROLE\_USER":

|   |The support works by associating the user to the `HttpServletRequest`.<br/>To associate the request to the `SecurityContextHolder` you need to ensure that the `SecurityContextPersistenceFilter` is associated with the `MockMvc` instance.<br/>A few ways to do this are:<br/><br/>* Invoking [`apply(springSecurity())`](setup.html#test-mockmvc-setup)<br/><br/>* Adding Spring Security’s `FilterChainProxy` to `MockMvc`<br/><br/>* Manually adding `SecurityContextPersistenceFilter` to the `MockMvc` instance may make sense when using `MockMvcBuilders.standaloneSetup`|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Java

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

Kotlin

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

You can easily make customizations.
For example, the following will run as a user (which does not need to exist) with the username "admin", the password "pass", and the roles "ROLE\_USER" and "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"))
}
```

If you have a custom `UserDetails` that you would like to use, you can easily specify that as well.
For example, the following will use the specified `UserDetails` (which does not need to exist) to run with a `UsernamePasswordAuthenticationToken` that has a principal of the specified `UserDetails`:

Java

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

Kotlin

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

You can run as anonymous user using the following:

Java

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

Kotlin

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

This is especially useful if you are running with a default user and wish to process a few requests as an anonymous user.

If you want a custom `Authentication` (which does not need to exist) you can do so using the following:

Java

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

Kotlin

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

You can even customize the `SecurityContext` using the following:

Java

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

Kotlin

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

We can also ensure to run as a specific user for every request by using `MockMvcBuilders`'s default request.
For example, the following will run as a user (which does not need to exist) with the username "admin", the password "password", and the role "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()
```

If you find you are using the same user in many of your tests, it is recommended to move the user to a method.
For example, you can specify the following in your own class named `CustomSecurityMockMvcRequestPostProcessors`:

Java

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

Kotlin

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

Now you can perform a static import on `CustomSecurityMockMvcRequestPostProcessors` and use that within your tests:

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

As an alternative to using a `RequestPostProcessor` to create your user, you can use annotations described in [Testing Method Security](../method.html).
For example, the following will run the test with the user with username "user", password "password", and role "ROLE\_USER":

Java

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

Kotlin

```
@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":

Java

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

Kotlin

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

[Security RequestPostProcessors](request-post-processors.html)[Mocking CSRF](csrf.html)