method.adoc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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 in order to access it.
  5. ====
  6. .Java
  7. [source,java,role="primary"]
  8. ----
  9. public class HelloMessageService implements MessageService {
  10. @PreAuthorize("authenticated")
  11. public String getMessage() {
  12. Authentication authentication = SecurityContextHolder.getContext()
  13. .getAuthentication();
  14. return "Hello " + authentication;
  15. }
  16. }
  17. ----
  18. .Kotlin
  19. [source,kotlin,role="secondary"]
  20. ----
  21. class HelloMessageService : MessageService {
  22. @PreAuthorize("authenticated")
  23. fun getMessage(): String {
  24. val authentication: Authentication = SecurityContextHolder.getContext().authentication
  25. return "Hello $authentication"
  26. }
  27. }
  28. ----
  29. ====
  30. The result of `getMessage` is a String saying "Hello" to the current Spring Security `Authentication`.
  31. An example of the output is displayed below.
  32. [source,text]
  33. ----
  34. 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
  35. ----
  36. [[test-method-setup]]
  37. == Security Test Setup
  38. Before we can use Spring Security Test support, we must perform some setup. An example can be seen below:
  39. ====
  40. .Java
  41. [source,java,role="primary"]
  42. ----
  43. @ExtendWith(SpringExtension.class) // <1>
  44. @ContextConfiguration // <2>
  45. public class WithMockUserTests {
  46. ----
  47. .Kotlin
  48. [source,kotlin,role="secondary"]
  49. ----
  50. @ExtendWith(SpringExtension.class)
  51. @ContextConfiguration
  52. class WithMockUserTests {
  53. ----
  54. This is a basic example of how to setup Spring Security Test. The highlights are:
  55. <1> `@ExtendWith` instructs the spring-test module that it should create an `ApplicationContext`. For additional information refer to https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#testcontext-junit-jupiter-extension[Spring reference].
  56. <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 https://docs.spring.io/spring-framework/docs/4.0.x/spring-framework-reference/htmlsingle/#testcontext-ctx-management[Spring Reference]
  57. NOTE: Spring Security hooks into Spring Test support using the `WithSecurityContextTestExecutionListener` which will ensure our tests are ran with the correct user.
  58. It does this by populating the `SecurityContextHolder` prior to running our tests.
  59. If you are using reactive method security, you will also need `ReactorContextTestExecutionListener` which populates `ReactiveSecurityContextHolder`.
  60. After the test is done, it will clear out the `SecurityContextHolder`.
  61. If you only need Spring Security related support, you can replace `@ContextConfiguration` with `@SecurityTestExecutionListeners`.
  62. Remember we added the `@PreAuthorize` annotation to our `HelloMessageService` and so it requires an authenticated user to invoke it.
  63. If we ran the following test, we would expect the following test will pass:
  64. ====
  65. .Java
  66. [source,java,role="primary"]
  67. ----
  68. @Test(expected = AuthenticationCredentialsNotFoundException.class)
  69. public void getMessageUnauthenticated() {
  70. messageService.getMessage();
  71. }
  72. ----
  73. .Kotlin
  74. [source,kotlin,role="secondary"]
  75. ----
  76. @Test(expected = AuthenticationCredentialsNotFoundException::class)
  77. fun getMessageUnauthenticated() {
  78. messageService.getMessage()
  79. }
  80. ----
  81. ====
  82. [[test-method-withmockuser]]
  83. == @WithMockUser
  84. The question is "How could we most easily run the test as a specific user?"
  85. The answer is to use `@WithMockUser`.
  86. The following test will be run as a user with the username "user", the password "password", and the roles "ROLE_USER".
  87. ====
  88. .Java
  89. [source,java,role="primary"]
  90. ----
  91. @Test
  92. @WithMockUser
  93. public void getMessageWithMockUser() {
  94. String message = messageService.getMessage();
  95. ...
  96. }
  97. ----
  98. .Kotlin
  99. [source,kotlin,role="secondary"]
  100. ----
  101. @Test
  102. @WithMockUser
  103. fun getMessageWithMockUser() {
  104. val message: String = messageService.getMessage()
  105. // ...
  106. }
  107. ----
  108. ====
  109. Specifically the following is true:
  110. * The user with the username "user" does not have to exist since we are mocking the user
  111. * The `Authentication` that is populated in the `SecurityContext` is of type `UsernamePasswordAuthenticationToken`
  112. * The principal on the `Authentication` is Spring Security's `User` object
  113. * The `User` will have the username of "user", the password "password", and a single `GrantedAuthority` named "ROLE_USER" is used.
  114. Our example is nice because we are able to leverage a lot of defaults.
  115. What if we wanted to run the test with a different username?
  116. The following test would run with the username "customUser". Again, the user does not need to actually exist.
  117. ====
  118. .Java
  119. [source,java,role="primary"]
  120. ----
  121. @Test
  122. @WithMockUser("customUsername")
  123. public void getMessageWithMockUserCustomUsername() {
  124. String message = messageService.getMessage();
  125. ...
  126. }
  127. ----
  128. .Kotlin
  129. [source,kotlin,role="secondary"]
  130. ----
  131. @Test
  132. @WithMockUser("customUsername")
  133. fun getMessageWithMockUserCustomUsername() {
  134. val message: String = messageService.getMessage()
  135. // ...
  136. }
  137. ----
  138. ====
  139. We can also easily customize the roles.
  140. For example, this test will be invoked with the username "admin" and the roles "ROLE_USER" and "ROLE_ADMIN".
  141. ====
  142. .Java
  143. [source,java,role="primary"]
  144. ----
  145. @Test
  146. @WithMockUser(username="admin",roles={"USER","ADMIN"})
  147. public void getMessageWithMockUserCustomUser() {
  148. String message = messageService.getMessage();
  149. ...
  150. }
  151. ----
  152. .Kotlin
  153. [source,kotlin,role="secondary"]
  154. ----
  155. @Test
  156. @WithMockUser(username="admin",roles=["USER","ADMIN"])
  157. fun getMessageWithMockUserCustomUser() {
  158. val message: String = messageService.getMessage()
  159. // ...
  160. }
  161. ----
  162. ====
  163. If we do not want the value to automatically be prefixed with ROLE_ we can leverage the authorities attribute.
  164. For example, this test will be invoked with the username "admin" and the authorities "USER" and "ADMIN".
  165. ====
  166. .Java
  167. [source,java,role="primary"]
  168. ----
  169. @Test
  170. @WithMockUser(username = "admin", authorities = { "ADMIN", "USER" })
  171. public void getMessageWithMockUserCustomAuthorities() {
  172. String message = messageService.getMessage();
  173. ...
  174. }
  175. ----
  176. .Kotlin
  177. [source,kotlin,role="secondary"]
  178. ----
  179. @Test
  180. @WithMockUser(username = "admin", authorities = ["ADMIN", "USER"])
  181. fun getMessageWithMockUserCustomUsername() {
  182. val message: String = messageService.getMessage()
  183. // ...
  184. }
  185. ----
  186. ====
  187. Of course it can be a bit tedious placing the annotation on every test method.
  188. Instead, we can place the annotation at the class level and every test will use the specified user.
  189. 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".
  190. ====
  191. .Java
  192. [source,java,role="primary"]
  193. ----
  194. @ExtendWith(SpringExtension.class)
  195. @ContextConfiguration
  196. @WithMockUser(username="admin",roles={"USER","ADMIN"})
  197. public class WithMockUserTests {
  198. ----
  199. .Kotlin
  200. [source,kotlin,role="secondary"]
  201. ----
  202. @ExtendWith(SpringExtension.class)
  203. @ContextConfiguration
  204. @WithMockUser(username="admin",roles=["USER","ADMIN"])
  205. class WithMockUserTests {
  206. ----
  207. ====
  208. 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.
  209. 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.
  210. ====
  211. .Java
  212. [source,java,role="primary"]
  213. ----
  214. @ExtendWith(SpringExtension.class)
  215. @ContextConfiguration
  216. @WithMockUser(username="admin",roles={"USER","ADMIN"})
  217. public class WithMockUserTests {
  218. @Nested
  219. public class TestSuite1 {
  220. // ... all test methods use admin user
  221. }
  222. @Nested
  223. public class TestSuite2 {
  224. // ... all test methods use admin user
  225. }
  226. }
  227. ----
  228. .Kotlin
  229. [source,kotlin,role="secondary"]
  230. ----
  231. @ExtendWith(SpringExtension::class)
  232. @ContextConfiguration
  233. @WithMockUser(username = "admin", roles = ["USER", "ADMIN"])
  234. class WithMockUserTests {
  235. @Nested
  236. inner class TestSuite1 { // ... all test methods use admin user
  237. }
  238. @Nested
  239. inner class TestSuite2 { // ... all test methods use admin user
  240. }
  241. }
  242. ----
  243. ====
  244. By default the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event.
  245. This is the equivalent of happening before JUnit's `@Before`.
  246. You can change this to happen during the `TestExecutionListener.beforeTestExecution` event which is after JUnit's `@Before` but before the test method is invoked.
  247. [source,java]
  248. ----
  249. @WithMockUser(setupBefore = TestExecutionEvent.TEST_EXECUTION)
  250. ----
  251. [[test-method-withanonymoususer]]
  252. == @WithAnonymousUser
  253. Using `@WithAnonymousUser` allows running as an anonymous user.
  254. 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.
  255. For example, the following will run withMockUser1 and withMockUser2 using <<test-method-withmockuser,@WithMockUser>> and anonymous as an anonymous user.
  256. ====
  257. .Java
  258. [source,java,role="primary"]
  259. ----
  260. @ExtendWith(SpringExtension.class)
  261. @WithMockUser
  262. public class WithUserClassLevelAuthenticationTests {
  263. @Test
  264. public void withMockUser1() {
  265. }
  266. @Test
  267. public void withMockUser2() {
  268. }
  269. @Test
  270. @WithAnonymousUser
  271. public void anonymous() throws Exception {
  272. // override default to run as anonymous user
  273. }
  274. }
  275. ----
  276. .Kotlin
  277. [source,kotlin,role="secondary"]
  278. ----
  279. @ExtendWith(SpringExtension.class)
  280. @WithMockUser
  281. class WithUserClassLevelAuthenticationTests {
  282. @Test
  283. fun withMockUser1() {
  284. }
  285. @Test
  286. fun withMockUser2() {
  287. }
  288. @Test
  289. @WithAnonymousUser
  290. fun anonymous() {
  291. // override default to run as anonymous user
  292. }
  293. }
  294. ----
  295. ====
  296. By default the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event.
  297. This is the equivalent of happening before JUnit's `@Before`.
  298. You can change this to happen during the `TestExecutionListener.beforeTestExecution` event which is after JUnit's `@Before` but before the test method is invoked.
  299. [source,java]
  300. ----
  301. @WithAnonymousUser(setupBefore = TestExecutionEvent.TEST_EXECUTION)
  302. ----
  303. [[test-method-withuserdetails]]
  304. == @WithUserDetails
  305. While `@WithMockUser` is a very convenient way to get started, it may not work in all instances.
  306. For example, it is common for applications to expect that the `Authentication` principal be of a specific type.
  307. This is done so that the application can refer to the principal as the custom type and reduce coupling on Spring Security.
  308. The custom principal is often times returned by a custom `UserDetailsService` that returns an object that implements both `UserDetails` and the custom type.
  309. For situations like this, it is useful to create the test user using the custom `UserDetailsService`.
  310. That is exactly what `@WithUserDetails` does.
  311. 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".
  312. ====
  313. .Java
  314. [source,java,role="primary"]
  315. ----
  316. @Test
  317. @WithUserDetails
  318. public void getMessageWithUserDetails() {
  319. String message = messageService.getMessage();
  320. ...
  321. }
  322. ----
  323. .Kotlin
  324. [source,kotlin,role="secondary"]
  325. ----
  326. @Test
  327. @WithUserDetails
  328. fun getMessageWithUserDetails() {
  329. val message: String = messageService.getMessage()
  330. // ...
  331. }
  332. ----
  333. ====
  334. We can also customize the username used to lookup the user from our `UserDetailsService`.
  335. For example, this test would be run with a principal that is returned from the `UserDetailsService` with the username of "customUsername".
  336. ====
  337. .Java
  338. [source,java,role="primary"]
  339. ----
  340. @Test
  341. @WithUserDetails("customUsername")
  342. public void getMessageWithUserDetailsCustomUsername() {
  343. String message = messageService.getMessage();
  344. ...
  345. }
  346. ----
  347. .Kotlin
  348. [source,kotlin,role="secondary"]
  349. ----
  350. @Test
  351. @WithUserDetails("customUsername")
  352. fun getMessageWithUserDetailsCustomUsername() {
  353. val message: String = messageService.getMessage()
  354. // ...
  355. }
  356. ----
  357. ====
  358. We can also provide an explicit bean name to look up the `UserDetailsService`.
  359. For example, this test would look up the username of "customUsername" using the `UserDetailsService` with the bean name "myUserDetailsService".
  360. ====
  361. .Java
  362. [source,java,role="primary"]
  363. ----
  364. @Test
  365. @WithUserDetails(value="customUsername", userDetailsServiceBeanName="myUserDetailsService")
  366. public void getMessageWithUserDetailsServiceBeanName() {
  367. String message = messageService.getMessage();
  368. ...
  369. }
  370. ----
  371. .Kotlin
  372. [source,kotlin,role="secondary"]
  373. ----
  374. @Test
  375. @WithUserDetails(value="customUsername", userDetailsServiceBeanName="myUserDetailsService")
  376. fun getMessageWithUserDetailsServiceBeanName() {
  377. val message: String = messageService.getMessage()
  378. // ...
  379. }
  380. ----
  381. ====
  382. Like `@WithMockUser` we can also place our annotation at the class level so that every test uses the same user.
  383. However unlike `@WithMockUser`, `@WithUserDetails` requires the user to exist.
  384. By default the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event.
  385. This is the equivalent of happening before JUnit's `@Before`.
  386. You can change this to happen during the `TestExecutionListener.beforeTestExecution` event which is after JUnit's `@Before` but before the test method is invoked.
  387. [source,java]
  388. ----
  389. @WithUserDetails(setupBefore = TestExecutionEvent.TEST_EXECUTION)
  390. ----
  391. [[test-method-withsecuritycontext]]
  392. == @WithSecurityContext
  393. We have seen that `@WithMockUser` is an excellent choice if we are not using a custom `Authentication` principal.
  394. Next we discovered that `@WithUserDetails` would allow us to use a custom `UserDetailsService` to create our `Authentication` principal but required the user to exist.
  395. We will now see an option that allows the most flexibility.
  396. We can create our own annotation that uses the `@WithSecurityContext` to create any `SecurityContext` we want.
  397. For example, we might create an annotation named `@WithMockCustomUser` as shown below:
  398. ====
  399. .Java
  400. [source,java,role="primary"]
  401. ----
  402. @Retention(RetentionPolicy.RUNTIME)
  403. @WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class)
  404. public @interface WithMockCustomUser {
  405. String username() default "rob";
  406. String name() default "Rob Winch";
  407. }
  408. ----
  409. .Kotlin
  410. [source,kotlin,role="secondary"]
  411. ----
  412. @Retention(AnnotationRetention.RUNTIME)
  413. @WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory::class)
  414. annotation class WithMockCustomUser(val username: String = "rob", val name: String = "Rob Winch")
  415. ----
  416. ====
  417. You can see that `@WithMockCustomUser` is annotated with the `@WithSecurityContext` annotation.
  418. This is what signals to Spring Security Test support that we intend to create a `SecurityContext` for the test.
  419. The `@WithSecurityContext` annotation requires we specify a `SecurityContextFactory` that will create a new `SecurityContext` given our `@WithMockCustomUser` annotation.
  420. You can find our `WithMockCustomUserSecurityContextFactory` implementation below:
  421. ====
  422. .Java
  423. [source,java,role="primary"]
  424. ----
  425. public class WithMockCustomUserSecurityContextFactory
  426. implements WithSecurityContextFactory<WithMockCustomUser> {
  427. @Override
  428. public SecurityContext createSecurityContext(WithMockCustomUser customUser) {
  429. SecurityContext context = SecurityContextHolder.createEmptyContext();
  430. CustomUserDetails principal =
  431. new CustomUserDetails(customUser.name(), customUser.username());
  432. Authentication auth =
  433. new UsernamePasswordAuthenticationToken(principal, "password", principal.getAuthorities());
  434. context.setAuthentication(auth);
  435. return context;
  436. }
  437. }
  438. ----
  439. .Kotlin
  440. [source,kotlin,role="secondary"]
  441. ----
  442. class WithMockCustomUserSecurityContextFactory : WithSecurityContextFactory<WithMockCustomUser> {
  443. override fun createSecurityContext(customUser: WithMockCustomUser): SecurityContext {
  444. val context = SecurityContextHolder.createEmptyContext()
  445. val principal = CustomUserDetails(customUser.name, customUser.username)
  446. val auth: Authentication =
  447. UsernamePasswordAuthenticationToken(principal, "password", principal.authorities)
  448. context.authentication = auth
  449. return context
  450. }
  451. }
  452. ----
  453. ====
  454. 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.
  455. When creating your own `WithSecurityContextFactory` implementations, it is nice to know that they can be annotated with standard Spring annotations.
  456. For example, the `WithUserDetailsSecurityContextFactory` uses the `@Autowired` annotation to acquire the `UserDetailsService`:
  457. ====
  458. .Java
  459. [source,java,role="primary"]
  460. ----
  461. final class WithUserDetailsSecurityContextFactory
  462. implements WithSecurityContextFactory<WithUserDetails> {
  463. private UserDetailsService userDetailsService;
  464. @Autowired
  465. public WithUserDetailsSecurityContextFactory(UserDetailsService userDetailsService) {
  466. this.userDetailsService = userDetailsService;
  467. }
  468. public SecurityContext createSecurityContext(WithUserDetails withUser) {
  469. String username = withUser.value();
  470. Assert.hasLength(username, "value() must be non-empty String");
  471. UserDetails principal = userDetailsService.loadUserByUsername(username);
  472. Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities());
  473. SecurityContext context = SecurityContextHolder.createEmptyContext();
  474. context.setAuthentication(authentication);
  475. return context;
  476. }
  477. }
  478. ----
  479. .Kotlin
  480. [source,kotlin,role="secondary"]
  481. ----
  482. class WithUserDetailsSecurityContextFactory @Autowired constructor(private val userDetailsService: UserDetailsService) :
  483. WithSecurityContextFactory<WithUserDetails> {
  484. override fun createSecurityContext(withUser: WithUserDetails): SecurityContext {
  485. val username: String = withUser.value
  486. Assert.hasLength(username, "value() must be non-empty String")
  487. val principal = userDetailsService.loadUserByUsername(username)
  488. val authentication: Authentication =
  489. UsernamePasswordAuthenticationToken(principal, principal.password, principal.authorities)
  490. val context = SecurityContextHolder.createEmptyContext()
  491. context.authentication = authentication
  492. return context
  493. }
  494. }
  495. ----
  496. ====
  497. By default the `SecurityContext` is set during the `TestExecutionListener.beforeTestMethod` event.
  498. This is the equivalent of happening before JUnit's `@Before`.
  499. You can change this to happen during the `TestExecutionListener.beforeTestExecution` event which is after JUnit's `@Before` but before the test method is invoked.
  500. [source,java]
  501. ----
  502. @WithSecurityContext(setupBefore = TestExecutionEvent.TEST_EXECUTION)
  503. ----
  504. [[test-method-meta-annotations]]
  505. == Test Meta Annotations
  506. If you reuse the same user within your tests often, it is not ideal to have to repeatedly specify the attributes.
  507. 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:
  508. ====
  509. .Java
  510. [source,java,role="primary"]
  511. ----
  512. @WithMockUser(username="admin",roles={"USER","ADMIN"})
  513. ----
  514. .Kotlin
  515. [source,kotlin,role="secondary"]
  516. ----
  517. @WithMockUser(username="admin",roles=["USER","ADMIN"])
  518. ----
  519. ====
  520. Rather than repeating this everywhere, we can use a meta annotation.
  521. For example, we could create a meta annotation named `WithMockAdmin`:
  522. ====
  523. .Java
  524. [source,java,role="primary"]
  525. ----
  526. @Retention(RetentionPolicy.RUNTIME)
  527. @WithMockUser(value="rob",roles="ADMIN")
  528. public @interface WithMockAdmin { }
  529. ----
  530. .Kotlin
  531. [source,kotlin,role="secondary"]
  532. ----
  533. @Retention(AnnotationRetention.RUNTIME)
  534. @WithMockUser(value = "rob", roles = ["ADMIN"])
  535. annotation class WithMockAdmin
  536. ----
  537. ====
  538. Now we can use `@WithMockAdmin` in the same way as the more verbose `@WithMockUser`.
  539. Meta annotations work with any of the testing annotations described above.
  540. For example, this means we could create a meta annotation for `@WithUserDetails("admin")` as well.