servlet-test-method.md 19.8 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 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
# Testing Method Security

This section demonstrates how to use Spring Security’s Test support to test method based security.
We first introduce a `MessageService` that requires the user to be authenticated in order to access it.

Java

```
public class HelloMessageService implements MessageService {

	@PreAuthorize("authenticated")
	public String getMessage() {
		Authentication authentication = SecurityContextHolder.getContext()
			.getAuthentication();
		return "Hello " + authentication;
	}
}
```

Kotlin

```
class HelloMessageService : MessageService {
    @PreAuthorize("authenticated")
    fun getMessage(): String {
        val authentication: Authentication = SecurityContextHolder.getContext().authentication
        return "Hello $authentication"
    }
}
```

The result of `getMessage` is a String saying "Hello" to the current Spring Security `Authentication`.
An example of the output is displayed below.

```
Hello org.springframew[email protected]ca25360: Principal: [email protected]: Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER
```

## Security Test Setup

Before we can use Spring Security Test support, we must perform some setup. An example can be seen below:

Java

```
@RunWith(SpringJUnit4ClassRunner.class) (1)
@ContextConfiguration (2)
public class WithMockUserTests {
```

Kotlin

```
@RunWith(SpringJUnit4ClassRunner::class)
@ContextConfiguration
class WithMockUserTests {
```

This is a basic example of how to setup Spring Security Test. The highlights are:

|**1**|                                               `@RunWith` instructs the spring-test module that it should create an `ApplicationContext`. This is no different than using the existing Spring Test support. For additional information, refer to the [Spring Reference](https://docs.spring.io/spring-framework/docs/4.0.x/spring-framework-reference/htmlsingle/#integration-testing-annotations-standard)                                               |
|-----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|**2**|`@ContextConfiguration` instructs the spring-test the configuration to use to create the `ApplicationContext`. Since no configuration is specified, the default configuration locations will be tried. This is no different than using the existing Spring Test support. For additional information, refer to the [Spring Reference](https://docs.spring.io/spring-framework/docs/4.0.x/spring-framework-reference/htmlsingle/#testcontext-ctx-management)|

|   |Spring Security hooks into Spring Test support using the `WithSecurityContextTestExecutionListener` which will ensure our tests are ran with the correct user.<br/>It does this by populating the `SecurityContextHolder` prior to running our tests.<br/>If you are using reactive method security, you will also need `ReactorContextTestExecutionListener` which populates `ReactiveSecurityContextHolder`.<br/>After the test is done, it will clear out the `SecurityContextHolder`.<br/>If you only need Spring Security related support, you can replace `@ContextConfiguration` with `@SecurityTestExecutionListeners`.|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

Remember we added the `@PreAuthorize` annotation to our `HelloMessageService` and so it requires an authenticated user to invoke it.
If we ran the following test, we would expect the following test will pass:

Java

```
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void getMessageUnauthenticated() {
	messageService.getMessage();
}
```

Kotlin

```
@Test(expected = AuthenticationCredentialsNotFoundException::class)
fun getMessageUnauthenticated() {
    messageService.getMessage()
}
```

## @WithMockUser

The question is "How could we most easily run the test as a specific user?"
The answer is to use `@WithMockUser`.
The following test will be run as a user with the username "user", the password "password", and the roles "ROLE\_USER".

Java

```
@Test
@WithMockUser
public void getMessageWithMockUser() {
String message = messageService.getMessage();
...
}
```

Kotlin

```
@Test
@WithMockUser
fun getMessageWithMockUser() {
    val message: String = messageService.getMessage()
    // ...
}
```

Specifically the following is true:

* The user with the username "user" does not have to exist since we are mocking the user

* The `Authentication` that is populated in the `SecurityContext` is of type `UsernamePasswordAuthenticationToken`

* The principal on the `Authentication` is Spring Security’s `User` object

* The `User` will have the username of "user", the password "password", and a single `GrantedAuthority` named "ROLE\_USER" is used.

Our example is nice because we are able to leverage a lot of defaults.
What if we wanted to run the test with a different username?
The following test would run with the username "customUser". Again, the user does not need to actually exist.

Java

```
@Test
@WithMockUser("customUsername")
public void getMessageWithMockUserCustomUsername() {
	String message = messageService.getMessage();
...
}
```

Kotlin

```
@Test
@WithMockUser("customUsername")
fun getMessageWithMockUserCustomUsername() {
    val message: String = messageService.getMessage()
    // ...
}
```

We can also easily customize the roles.
For example, this test will be invoked with the username "admin" and the roles "ROLE\_USER" and "ROLE\_ADMIN".

Java

```
@Test
@WithMockUser(username="admin",roles={"USER","ADMIN"})
public void getMessageWithMockUserCustomUser() {
	String message = messageService.getMessage();
	...
}
```

Kotlin

```
@Test
@WithMockUser(username="admin",roles=["USER","ADMIN"])
fun getMessageWithMockUserCustomUser() {
    val message: String = messageService.getMessage()
    // ...
}
```

If we do not want the value to automatically be prefixed with ROLE\_ we can leverage the authorities attribute.
For example, this test will be invoked with the username "admin" and the authorities "USER" and "ADMIN".

Java

```
@Test
@WithMockUser(username = "admin", authorities = { "ADMIN", "USER" })
public void getMessageWithMockUserCustomAuthorities() {
	String message = messageService.getMessage();
	...
}
```

Kotlin

```
@Test
@WithMockUser(username = "admin", authorities = ["ADMIN", "USER"])
fun getMessageWithMockUserCustomUsername() {
    val message: String = messageService.getMessage()
    // ...
}
```

Of course it can be a bit tedious placing the annotation on every test method.
Instead, we can place the annotation at the class level and every test will use the specified user.
For example, the following would run every test with a user with the username "admin", the password "password", and the roles "ROLE\_USER" and "ROLE\_ADMIN".

Java

```
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WithMockUser(username="admin",roles={"USER","ADMIN"})
public class WithMockUserTests {
```

Kotlin

```
@RunWith(SpringJUnit4ClassRunner::class)
@ContextConfiguration
@WithMockUser(username="admin",roles=["USER","ADMIN"])
class WithMockUserTests {
```

If you are using JUnit 5’s `@Nested` test support, you can also place the annotation on the enclosing class to apply to all nested classes.
For example, the following would run every test with a user with the username "admin", the password "password", and the roles "ROLE\_USER" and "ROLE\_ADMIN" for both test methods.

Java

```
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@WithMockUser(username="admin",roles={"USER","ADMIN"})
public class WithMockUserTests {

	@Nested
	public class TestSuite1 {
		// ... all test methods use admin user
	}

	@Nested
	public class TestSuite2 {
		// ... all test methods use admin user
	}
}
```

Kotlin

```
@ExtendWith(SpringExtension::class)
@ContextConfiguration
@WithMockUser(username = "admin", roles = ["USER", "ADMIN"])
class WithMockUserTests {
    @Nested
    inner class TestSuite1 { // ... all test methods use admin user
    }

    @Nested
    inner class TestSuite2 { // ... all test methods use admin user
    }
}
```

By default the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event.
This is the equivalent of happening before JUnit’s `@Before`.
You can change this to happen during the `TestExecutionListener.beforeTestExecution` event which is after JUnit’s `@Before` but before the test method is invoked.

```
@WithMockUser(setupBefore = TestExecutionEvent.TEST_EXECUTION)
```

## @WithAnonymousUser

Using `@WithAnonymousUser` allows running as an anonymous user.
This is especially convenient when you wish to run most of your tests with a specific user, but want to run a few tests as an anonymous user.
For example, the following will run withMockUser1 and withMockUser2 using [@WithMockUser](#test-method-withmockuser) and anonymous as an anonymous user.

Java

```
@RunWith(SpringJUnit4ClassRunner.class)
@WithMockUser
public class WithUserClassLevelAuthenticationTests {

	@Test
	public void withMockUser1() {
	}

	@Test
	public void withMockUser2() {
	}

	@Test
	@WithAnonymousUser
	public void anonymous() throws Exception {
		// override default to run as anonymous user
	}
}
```

Kotlin

```
@RunWith(SpringJUnit4ClassRunner::class)
@WithMockUser
class WithUserClassLevelAuthenticationTests {
    @Test
    fun withMockUser1() {
    }

    @Test
    fun withMockUser2() {
    }

    @Test
    @WithAnonymousUser
    fun anonymous() {
        // override default to run as anonymous user
    }
}
```

By default the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event.
This is the equivalent of happening before JUnit’s `@Before`.
You can change this to happen during the `TestExecutionListener.beforeTestExecution` event which is after JUnit’s `@Before` but before the test method is invoked.

```
@WithAnonymousUser(setupBefore = TestExecutionEvent.TEST_EXECUTION)
```

## @WithUserDetails

While `@WithMockUser` is a very convenient way to get started, it may not work in all instances.
For example, it is common for applications to expect that the `Authentication` principal be of a specific type.
This is done so that the application can refer to the principal as the custom type and reduce coupling on Spring Security.

The custom principal is often times returned by a custom `UserDetailsService` that returns an object that implements both `UserDetails` and the custom type.
For situations like this, it is useful to create the test user using the custom `UserDetailsService`.
That is exactly what `@WithUserDetails` does.

Assuming we have a `UserDetailsService` exposed as a bean, the following test will be invoked with an `Authentication` of type `UsernamePasswordAuthenticationToken` and a principal that is returned from the `UserDetailsService` with the username of "user".

Java

```
@Test
@WithUserDetails
public void getMessageWithUserDetails() {
	String message = messageService.getMessage();
	...
}
```

Kotlin

```
@Test
@WithUserDetails
fun getMessageWithUserDetails() {
    val message: String = messageService.getMessage()
    // ...
}
```

We can also customize the username used to lookup the user from our `UserDetailsService`.
For example, this test would be run with a principal that is returned from the `UserDetailsService` with the username of "customUsername".

Java

```
@Test
@WithUserDetails("customUsername")
public void getMessageWithUserDetailsCustomUsername() {
	String message = messageService.getMessage();
	...
}
```

Kotlin

```
@Test
@WithUserDetails("customUsername")
fun getMessageWithUserDetailsCustomUsername() {
    val message: String = messageService.getMessage()
    // ...
}
```

We can also provide an explicit bean name to look up the `UserDetailsService`.
For example, this test would look up the username of "customUsername" using the `UserDetailsService` with the bean name "myUserDetailsService".

Java

```
@Test
@WithUserDetails(value="customUsername", userDetailsServiceBeanName="myUserDetailsService")
public void getMessageWithUserDetailsServiceBeanName() {
	String message = messageService.getMessage();
	...
}
```

Kotlin

```
@Test
@WithUserDetails(value="customUsername", userDetailsServiceBeanName="myUserDetailsService")
fun getMessageWithUserDetailsServiceBeanName() {
    val message: String = messageService.getMessage()
    // ...
}
```

Like `@WithMockUser` we can also place our annotation at the class level so that every test uses the same user.
However unlike `@WithMockUser`, `@WithUserDetails` requires the user to exist.

By default the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event.
This is the equivalent of happening before JUnit’s `@Before`.
You can change this to happen during the `TestExecutionListener.beforeTestExecution` event which is after JUnit’s `@Before` but before the test method is invoked.

```
@WithUserDetails(setupBefore = TestExecutionEvent.TEST_EXECUTION)
```

## @WithSecurityContext

We have seen that `@WithMockUser` is an excellent choice if we are not using a custom `Authentication` principal.
Next we discovered that `@WithUserDetails` would allow us to use a custom `UserDetailsService` to create our `Authentication` principal but required the user to exist.
We will now see an option that allows the most flexibility.

We can create our own annotation that uses the `@WithSecurityContext` to create any `SecurityContext` we want.
For example, we might create an annotation named `@WithMockCustomUser` as shown below:

Java

```
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class)
public @interface WithMockCustomUser {

	String username() default "rob";

	String name() default "Rob Winch";
}
```

Kotlin

```
@Retention(AnnotationRetention.RUNTIME)
@WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory::class)
annotation class WithMockCustomUser(val username: String = "rob", val name: String = "Rob Winch")
```

You can see that `@WithMockCustomUser` is annotated with the `@WithSecurityContext` annotation.
This is what signals to Spring Security Test support that we intend to create a `SecurityContext` for the test.
The `@WithSecurityContext` annotation requires we specify a `SecurityContextFactory` that will create a new `SecurityContext` given our `@WithMockCustomUser` annotation.
You can find our `WithMockCustomUserSecurityContextFactory` implementation below:

Java

```
public class WithMockCustomUserSecurityContextFactory
	implements WithSecurityContextFactory<WithMockCustomUser> {
	@Override
	public SecurityContext createSecurityContext(WithMockCustomUser customUser) {
		SecurityContext context = SecurityContextHolder.createEmptyContext();

		CustomUserDetails principal =
			new CustomUserDetails(customUser.name(), customUser.username());
		Authentication auth =
			new UsernamePasswordAuthenticationToken(principal, "password", principal.getAuthorities());
		context.setAuthentication(auth);
		return context;
	}
}
```

Kotlin

```
class WithMockCustomUserSecurityContextFactory : WithSecurityContextFactory<WithMockCustomUser> {
    override fun createSecurityContext(customUser: WithMockCustomUser): SecurityContext {
        val context = SecurityContextHolder.createEmptyContext()
        val principal = CustomUserDetails(customUser.name, customUser.username)
        val auth: Authentication =
            UsernamePasswordAuthenticationToken(principal, "password", principal.authorities)
        context.authentication = auth
        return context
    }
}
```

We can now annotate a test class or a test method with our new annotation and Spring Security’s `WithSecurityContextTestExecutionListener` will ensure that our `SecurityContext` is populated appropriately.

When creating your own `WithSecurityContextFactory` implementations, it is nice to know that they can be annotated with standard Spring annotations.
For example, the `WithUserDetailsSecurityContextFactory` uses the `@Autowired` annotation to acquire the `UserDetailsService`:

Java

```
final class WithUserDetailsSecurityContextFactory
	implements WithSecurityContextFactory<WithUserDetails> {

	private UserDetailsService userDetailsService;

	@Autowired
	public WithUserDetailsSecurityContextFactory(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	public SecurityContext createSecurityContext(WithUserDetails withUser) {
		String username = withUser.value();
		Assert.hasLength(username, "value() must be non-empty String");
		UserDetails principal = userDetailsService.loadUserByUsername(username);
		Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities());
		SecurityContext context = SecurityContextHolder.createEmptyContext();
		context.setAuthentication(authentication);
		return context;
	}
}
```

Kotlin

```
class WithUserDetailsSecurityContextFactory @Autowired constructor(private val userDetailsService: UserDetailsService) :
    WithSecurityContextFactory<WithUserDetails> {
    override fun createSecurityContext(withUser: WithUserDetails): SecurityContext {
        val username: String = withUser.value
        Assert.hasLength(username, "value() must be non-empty String")
        val principal = userDetailsService.loadUserByUsername(username)
        val authentication: Authentication =
            UsernamePasswordAuthenticationToken(principal, principal.password, principal.authorities)
        val context = SecurityContextHolder.createEmptyContext()
        context.authentication = authentication
        return context
    }
}
```

By default the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event.
This is the equivalent of happening before JUnit’s `@Before`.
You can change this to happen during the `TestExecutionListener.beforeTestExecution` event which is after JUnit’s `@Before` but before the test method is invoked.

```
@WithSecurityContext(setupBefore = TestExecutionEvent.TEST_EXECUTION)
```

## Test Meta Annotations

If you reuse the same user within your tests often, it is not ideal to have to repeatedly specify the attributes.
For example, if there are many tests related to an administrative user with the username "admin" and the roles `ROLE_USER` and `ROLE_ADMIN` you would have to write:

Java

```
@WithMockUser(username="admin",roles={"USER","ADMIN"})
```

Kotlin

```
@WithMockUser(username="admin",roles=["USER","ADMIN"])
```

Rather than repeating this everywhere, we can use a meta annotation.
For example, we could create a meta annotation named `WithMockAdmin`:

Java

```
@Retention(RetentionPolicy.RUNTIME)
@WithMockUser(value="rob",roles="ADMIN")
public @interface WithMockAdmin { }
```

Kotlin

```
@Retention(AnnotationRetention.RUNTIME)
@WithMockUser(value = "rob", roles = ["ADMIN"])
annotation class WithMockAdmin
```

Now we can use `@WithMockAdmin` in the same way as the more verbose `@WithMockUser`.

Meta annotations work with any of the testing annotations described above.
For example, this means we could create a meta annotation for `@WithUserDetails("admin")` as well.

[Testing](index.html)[MockMvc Support](mockmvc/index.html)