method.adoc 20 KB

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