method.adoc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. [[test-method]]
  2. = Testing Method Security
  3. This section demonstrates how to use Spring Security's Test support to test method-based security.
  4. We first introduce a `MessageService` that requires the user to be authenticated to be able to access it:
  5. include-code::./HelloMessageService[tag=authenticated,indent=0]
  6. The result of `getMessage` is a `String` that says "`Hello`" to the current Spring Security `Authentication`.
  7. The following listing shows example output:
  8. [source,text]
  9. ----
  10. Hello org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ca25360: Principal: org.springframework.security.core.userdetails.User@36ebcb: 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
  11. ----
  12. [[test-method-setup]]
  13. == Security Test Setup
  14. Before we can use the Spring Security test support, we must perform some setup:
  15. include-code::./WithMockUserTests[tag=setup,indent=0]
  16. <1> `@ExtendWith` instructs the spring-test module that it should create an `ApplicationContext`. For additional information, refer to the {spring-framework-reference-url}testing.html#testcontext-junit-jupiter-extension[Spring reference].
  17. <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-framework-reference-url}testing.html#spring-testing-annotation-contextconfiguration[Spring Reference].
  18. [NOTE]
  19. ====
  20. Spring Security hooks into Spring Test support through the `WithSecurityContextTestExecutionListener`, which ensures that our tests are run with the correct user.
  21. It does this by populating the `SecurityContextHolder` prior to running our tests.
  22. If you use reactive method security, you also need `ReactorContextTestExecutionListener`, which populates `ReactiveSecurityContextHolder`.
  23. After the test is done, it clears out the `SecurityContextHolder`.
  24. If you need only Spring Security related support, you can replace `@ContextConfiguration` with `@SecurityTestExecutionListeners`.
  25. ====
  26. Remember, we added the `@PreAuthorize` annotation to our `HelloMessageService`, so it requires an authenticated user to invoke it.
  27. If we run the tests, we expect the following test will pass:
  28. include-code::./WithMockUserSampleTests[tag=snippet,indent=0]
  29. [[test-method-withmockuser]]
  30. == @WithMockUser
  31. The question is "How could we most easily run the test as a specific user?"
  32. The answer is to use `@WithMockUser`.
  33. The following test will be run as a user with the username "user", the password "password", and the roles "ROLE_USER".
  34. include-code::./WithMockUserTests[tag=mock-user,indent=0]
  35. Specifically the following is true:
  36. * The user with a username of `user` does not have to exist, since we mock the user object.
  37. * The `Authentication` that is populated in the `SecurityContext` is of type `UsernamePasswordAuthenticationToken`.
  38. * The principal on the `Authentication` is Spring Security's `User` object.
  39. * The `User` has a username of `user`.
  40. * The `User` has a password of `password`.
  41. * A single `GrantedAuthority` named `ROLE_USER` is used.
  42. The preceding example is handy, because it lets us use a lot of defaults.
  43. What if we wanted to run the test with a different username?
  44. The following test would run with a username of `customUser` (again, the user does not need to actually exist):
  45. include-code::./WithMockUserTests[tag=custom-user,indent=0]
  46. We can also easily customize the roles.
  47. For example, the following test is invoked with a username of `admin` and roles of `ROLE_USER` and `ROLE_ADMIN`.
  48. include-code::./WithMockUserTests[tag=custom-roles,indent=0]
  49. If we do not want the value to automatically be prefixed with `ROLE_` we can use the `authorities` attribute.
  50. For example, the following test is invoked with a username of `admin` and the `USER` and `ADMIN` authorities.
  51. include-code::./WithMockUserTests[tag=custom-authorities,indent=0]
  52. It can be a bit tedious to place the annotation on every test method.
  53. Instead, we can place the annotation at the class level. Then every test uses the specified user.
  54. The following example runs every test with a user whose username is `admin`, whose password is `password`, and who has the `ROLE_USER` and `ROLE_ADMIN` roles:
  55. include-code::./WithMockUserClassTests[tag=snippet,indent=0]
  56. If you use JUnit 5's `@Nested` test support, you can also place the annotation on the enclosing class to apply to all nested classes.
  57. The following example runs every test with a user whose username is `admin`, whose password is `password`, and who has the `ROLE_USER` and `ROLE_ADMIN` roles for both test methods.
  58. include-code::./WithMockUserNestedTests[tag=snippet,indent=0]
  59. By default, the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event.
  60. This is the equivalent of happening before JUnit's `@Before`.
  61. You can change this to happen during the `TestExecutionListener.beforeTestExecution` event, which is after JUnit's `@Before` but before the test method is invoked:
  62. [source,java]
  63. ----
  64. @WithMockUser(setupBefore = TestExecutionEvent.TEST_EXECUTION)
  65. ----
  66. [[test-method-withanonymoususer]]
  67. == @WithAnonymousUser
  68. Using `@WithAnonymousUser` allows running as an anonymous user.
  69. 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.
  70. The following example runs `withMockUser1` and `withMockUser2` by using <<test-method-withmockuser,@WithMockUser>> and `anonymous` as an anonymous user:
  71. include-code::./WithUserClassLevelAuthenticationTests[tag=snippet,indent=0]
  72. By default, the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event.
  73. This is the equivalent of happening before JUnit's `@Before`.
  74. You can change this to happen during the `TestExecutionListener.beforeTestExecution` event, which is after JUnit's `@Before` but before the test method is invoked:
  75. [source,java]
  76. ----
  77. @WithAnonymousUser(setupBefore = TestExecutionEvent.TEST_EXECUTION)
  78. ----
  79. [[test-method-withuserdetails]]
  80. == @WithUserDetails
  81. While `@WithMockUser` is a convenient way to get started, it may not work in all instances.
  82. For example, some applications expect the `Authentication` principal to be of a specific type.
  83. This is done so that the application can refer to the principal as the custom type and reduce coupling on Spring Security.
  84. The custom principal is often returned by a custom `UserDetailsService` that returns an object that implements both `UserDetails` and the custom type.
  85. For situations like this, it is useful to create the test user by using a custom `UserDetailsService`.
  86. That is exactly what `@WithUserDetails` does.
  87. Assuming we have a `UserDetailsService` exposed as a bean, the following test is invoked with an `Authentication` of type `UsernamePasswordAuthenticationToken` and a principal that is returned from the `UserDetailsService` with the username of `user`:
  88. include-code::./WithUserDetailsTests[tag=user-details,indent=0]
  89. We can also customize the username used to lookup the user from our `UserDetailsService`.
  90. For example, this test can be run with a principal that is returned from the `UserDetailsService` with the username of `customUsername`:
  91. include-code::./WithUserDetailsTests[tag=user-details-custom-username,indent=0]
  92. We can also provide an explicit bean name to look up the `UserDetailsService`.
  93. The following test looks up the username of `customUsername` by using the `UserDetailsService` with a bean name of `myUserDetailsService`:
  94. include-code::./WithCustomUserDetailsTests[tag=custom-user-details-service,indent=0]
  95. As we did with `@WithMockUser`, we can also place our annotation at the class level so that every test uses the same user.
  96. However, unlike `@WithMockUser`, `@WithUserDetails` requires the user to exist.
  97. By default, the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event.
  98. This is the equivalent of happening before JUnit's `@Before`.
  99. You can change this to happen during the `TestExecutionListener.beforeTestExecution` event, which is after JUnit's `@Before` but before the test method is invoked:
  100. [source,java]
  101. ----
  102. @WithUserDetails(setupBefore = TestExecutionEvent.TEST_EXECUTION)
  103. ----
  104. [[test-method-withsecuritycontext]]
  105. == @WithSecurityContext
  106. We have seen that `@WithMockUser` is an excellent choice if we do not use a custom `Authentication` principal.
  107. Next, we discovered that `@WithUserDetails` lets us use a custom `UserDetailsService` to create our `Authentication` principal but requires the user to exist.
  108. We now see an option that allows the most flexibility.
  109. We can create our own annotation that uses the `@WithSecurityContext` to create any `SecurityContext` we want.
  110. For example, we might create an annotation named `@WithMockCustomUser`:
  111. include-code::./WithMockCustomUser[tag=snippet,indent=0]
  112. You can see that `@WithMockCustomUser` is annotated with the `@WithSecurityContext` annotation.
  113. This is what signals to Spring Security test support that we intend to create a `SecurityContext` for the test.
  114. The `@WithSecurityContext` annotation requires that we specify a `SecurityContextFactory` to create a new `SecurityContext`, given our `@WithMockCustomUser` annotation.
  115. The following listing shows our `WithMockCustomUserSecurityContextFactory` implementation:
  116. include-code::./WithMockCustomUserSecurityContextFactory[tag=snippet,indent=0]
  117. We can now annotate a test class or a test method with our new annotation and Spring Security's `WithSecurityContextTestExecutionListener` to ensure that our `SecurityContext` is populated appropriately.
  118. When creating your own `WithSecurityContextFactory` implementations, it is nice to know that they can be annotated with standard Spring annotations.
  119. For example, the `WithUserDetailsSecurityContextFactory` uses the `@Autowired` annotation to acquire the `UserDetailsService`:
  120. include-code::./WithUserDetailsSecurityContextFactory[tag=snippet,indent=0]
  121. By default, the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event.
  122. This is the equivalent of happening before JUnit's `@Before`.
  123. You can change this to happen during the `TestExecutionListener.beforeTestExecution` event, which is after JUnit's `@Before` but before the test method is invoked:
  124. [source,java]
  125. ----
  126. @WithSecurityContext(setupBefore = TestExecutionEvent.TEST_EXECUTION)
  127. ----
  128. [[test-method-meta-annotations]]
  129. == Test Meta Annotations
  130. If you reuse the same user within your tests often, it is not ideal to have to repeatedly specify the attributes.
  131. For example, if you have many tests related to an administrative user with a username of `admin` and roles of `ROLE_USER` and `ROLE_ADMIN`, you have to write:
  132. include-code::./WithMockUserTests[tag=snippet,indent=0]
  133. Rather than repeating this everywhere, we can use a meta annotation.
  134. For example, we could create a meta annotation named `WithMockAdmin`:
  135. include-code::./WithMockAdmin[tag=snippet,indent=0]
  136. Now we can use `@WithMockAdmin` in the same way as the more verbose `@WithMockUser`.
  137. Meta annotations work with any of the testing annotations described above.
  138. For example, this means we could create a meta annotation for `@WithUserDetails("admin")` as well.