concurrency.adoc 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. [[concurrency]]
  2. = Concurrency Support
  3. In most environments, Security is stored on a per `Thread` basis.
  4. This means that when work is done on a new `Thread`, the `SecurityContext` is lost.
  5. Spring Security provides some infrastructure to help make this much easier for users.
  6. Spring Security provides low level abstractions for working with Spring Security in multi-threaded environments.
  7. In fact, this is what Spring Security builds on to integration with xref:servlet/integrations/servlet-api.adoc#servletapi-start-runnable[AsyncContext.start(Runnable)] and xref:servlet/integrations/mvc.adoc#mvc-async[Spring MVC Async Integration].
  8. == DelegatingSecurityContextRunnable
  9. One of the most fundamental building blocks within Spring Security's concurrency support is the `DelegatingSecurityContextRunnable`.
  10. It wraps a delegate `Runnable` in order to initialize the `SecurityContextHolder` with a specified `SecurityContext` for the delegate.
  11. It then invokes the delegate Runnable ensuring to clear the `SecurityContextHolder` afterwards.
  12. The `DelegatingSecurityContextRunnable` looks something like this:
  13. ====
  14. .Java
  15. [source,java,role="primary"]
  16. ----
  17. public void run() {
  18. try {
  19. SecurityContextHolder.setContext(securityContext);
  20. delegate.run();
  21. } finally {
  22. SecurityContextHolder.clearContext();
  23. }
  24. }
  25. ----
  26. .Kotlin
  27. [source,kotlin,role="secondary"]
  28. ----
  29. fun run() {
  30. try {
  31. SecurityContextHolder.setContext(securityContext)
  32. delegate.run()
  33. } finally {
  34. SecurityContextHolder.clearContext()
  35. }
  36. }
  37. ----
  38. ====
  39. While very simple, it makes it seamless to transfer the SecurityContext from one Thread to another.
  40. This is important since, in most cases, the SecurityContextHolder acts on a per Thread basis.
  41. For example, you might have used Spring Security's xref:servlet/appendix/namespace/method-security.adoc#nsa-global-method-security[<global-method-security>] support to secure one of your services.
  42. You can now easily transfer the `SecurityContext` of the current `Thread` to the `Thread` that invokes the secured service.
  43. An example of how you might do this can be found below:
  44. ====
  45. .Java
  46. [source,java,role="primary"]
  47. ----
  48. Runnable originalRunnable = new Runnable() {
  49. public void run() {
  50. // invoke secured service
  51. }
  52. };
  53. SecurityContext context = SecurityContextHolder.getContext();
  54. DelegatingSecurityContextRunnable wrappedRunnable =
  55. new DelegatingSecurityContextRunnable(originalRunnable, context);
  56. new Thread(wrappedRunnable).start();
  57. ----
  58. .Kotlin
  59. [source,kotlin,role="secondary"]
  60. ----
  61. val originalRunnable = Runnable {
  62. // invoke secured service
  63. }
  64. val context: SecurityContext = SecurityContextHolder.getContext()
  65. val wrappedRunnable = DelegatingSecurityContextRunnable(originalRunnable, context)
  66. Thread(wrappedRunnable).start()
  67. ----
  68. ====
  69. The code above performs the following steps:
  70. * Creates a `Runnable` that will be invoking our secured service.
  71. Notice that it is not aware of Spring Security
  72. * Obtains the `SecurityContext` that we wish to use from the `SecurityContextHolder` and initializes the `DelegatingSecurityContextRunnable`
  73. * Use the `DelegatingSecurityContextRunnable` to create a Thread
  74. * Start the Thread we created
  75. Since it is quite common to create a `DelegatingSecurityContextRunnable` with the `SecurityContext` from the `SecurityContextHolder` there is a shortcut constructor for it.
  76. The following code is the same as the code above:
  77. ====
  78. .Java
  79. [source,java,role="primary"]
  80. ----
  81. Runnable originalRunnable = new Runnable() {
  82. public void run() {
  83. // invoke secured service
  84. }
  85. };
  86. DelegatingSecurityContextRunnable wrappedRunnable =
  87. new DelegatingSecurityContextRunnable(originalRunnable);
  88. new Thread(wrappedRunnable).start();
  89. ----
  90. .Kotlin
  91. [source,kotlin,role="secondary"]
  92. ----
  93. val originalRunnable = Runnable {
  94. // invoke secured service
  95. }
  96. val wrappedRunnable = DelegatingSecurityContextRunnable(originalRunnable)
  97. Thread(wrappedRunnable).start()
  98. ----
  99. ====
  100. The code we have is simple to use, but it still requires knowledge that we are using Spring Security.
  101. In the next section we will take a look at how we can utilize `DelegatingSecurityContextExecutor` to hide the fact that we are using Spring Security.
  102. == DelegatingSecurityContextExecutor
  103. In the previous section we found that it was easy to use the `DelegatingSecurityContextRunnable`, but it was not ideal since we had to be aware of Spring Security in order to use it.
  104. Let's take a look at how `DelegatingSecurityContextExecutor` can shield our code from any knowledge that we are using Spring Security.
  105. The design of `DelegatingSecurityContextExecutor` is very similar to that of `DelegatingSecurityContextRunnable` except it accepts a delegate `Executor` instead of a delegate `Runnable`.
  106. You can see an example of how it might be used below:
  107. ====
  108. .Java
  109. [source,java,role="primary"]
  110. ----
  111. SecurityContext context = SecurityContextHolder.createEmptyContext();
  112. Authentication authentication =
  113. UsernamePasswordAuthenticationToken.authenticated("user","doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER"));
  114. context.setAuthentication(authentication);
  115. SimpleAsyncTaskExecutor delegateExecutor =
  116. new SimpleAsyncTaskExecutor();
  117. DelegatingSecurityContextExecutor executor =
  118. new DelegatingSecurityContextExecutor(delegateExecutor, context);
  119. Runnable originalRunnable = new Runnable() {
  120. public void run() {
  121. // invoke secured service
  122. }
  123. };
  124. executor.execute(originalRunnable);
  125. ----
  126. .Kotlin
  127. [source,kotlin,role="secondary"]
  128. ----
  129. val context: SecurityContext = SecurityContextHolder.createEmptyContext()
  130. val authentication: Authentication =
  131. UsernamePasswordAuthenticationToken("user", "doesnotmatter", AuthorityUtils.createAuthorityList("ROLE_USER"))
  132. context.authentication = authentication
  133. val delegateExecutor = SimpleAsyncTaskExecutor()
  134. val executor = DelegatingSecurityContextExecutor(delegateExecutor, context)
  135. val originalRunnable = Runnable {
  136. // invoke secured service
  137. }
  138. executor.execute(originalRunnable)
  139. ----
  140. ====
  141. The code performs the following steps:
  142. * Creates the `SecurityContext` to be used for our `DelegatingSecurityContextExecutor`.
  143. Note that in this example we simply create the `SecurityContext` by hand.
  144. However, it does not matter where or how we get the `SecurityContext` (i.e. we could obtain it from the `SecurityContextHolder` if we wanted).
  145. * Creates a delegateExecutor that is in charge of executing submitted ``Runnable``s
  146. * Finally we create a `DelegatingSecurityContextExecutor` which is in charge of wrapping any Runnable that is passed into the execute method with a `DelegatingSecurityContextRunnable`.
  147. It then passes the wrapped Runnable to the delegateExecutor.
  148. In this instance, the same `SecurityContext` will be used for every Runnable submitted to our `DelegatingSecurityContextExecutor`.
  149. This is nice if we are running background tasks that need to be run by a user with elevated privileges.
  150. * At this point you may be asking yourself "How does this shield my code of any knowledge of Spring Security?" Instead of creating the `SecurityContext` and the `DelegatingSecurityContextExecutor` in our own code, we can inject an already initialized instance of `DelegatingSecurityContextExecutor`.
  151. ====
  152. .Java
  153. [source,java,role="primary"]
  154. ----
  155. @Autowired
  156. private Executor executor; // becomes an instance of our DelegatingSecurityContextExecutor
  157. public void submitRunnable() {
  158. Runnable originalRunnable = new Runnable() {
  159. public void run() {
  160. // invoke secured service
  161. }
  162. };
  163. executor.execute(originalRunnable);
  164. }
  165. ----
  166. .Kotlin
  167. [source,kotlin,role="secondary"]
  168. ----
  169. @Autowired
  170. lateinit var executor: Executor // becomes an instance of our DelegatingSecurityContextExecutor
  171. fun submitRunnable() {
  172. val originalRunnable = Runnable {
  173. // invoke secured service
  174. }
  175. executor.execute(originalRunnable)
  176. }
  177. ----
  178. ====
  179. Now our code is unaware that the `SecurityContext` is being propagated to the `Thread`, then the `originalRunnable` is run, and then the `SecurityContextHolder` is cleared out.
  180. In this example, the same user is being used to run each thread.
  181. What if we wanted to use the user from `SecurityContextHolder` at the time we invoked `executor.execute(Runnable)` (i.e. the currently logged in user) to process ``originalRunnable``?
  182. This can be done by removing the `SecurityContext` argument from our `DelegatingSecurityContextExecutor` constructor.
  183. For example:
  184. ====
  185. .Java
  186. [source,java,role="primary"]
  187. ----
  188. SimpleAsyncTaskExecutor delegateExecutor = new SimpleAsyncTaskExecutor();
  189. DelegatingSecurityContextExecutor executor =
  190. new DelegatingSecurityContextExecutor(delegateExecutor);
  191. ----
  192. .Kotlin
  193. [source,kotlin,role="secondary"]
  194. ----
  195. val delegateExecutor = SimpleAsyncTaskExecutor()
  196. val executor = DelegatingSecurityContextExecutor(delegateExecutor)
  197. ----
  198. ====
  199. Now anytime `executor.execute(Runnable)` is executed the `SecurityContext` is first obtained by the `SecurityContextHolder` and then that `SecurityContext` is used to create our `DelegatingSecurityContextRunnable`.
  200. This means that we are running our `Runnable` with the same user that was used to invoke the `executor.execute(Runnable)` code.
  201. == Spring Security Concurrency Classes
  202. Refer to the Javadoc for additional integrations with both the Java concurrent APIs and the Spring Task abstractions.
  203. They are quite self-explanatory once you understand the previous code.
  204. * `DelegatingSecurityContextCallable`
  205. * `DelegatingSecurityContextExecutor`
  206. * `DelegatingSecurityContextExecutorService`
  207. * `DelegatingSecurityContextRunnable`
  208. * `DelegatingSecurityContextScheduledExecutorService`
  209. * `DelegatingSecurityContextSchedulingTaskExecutor`
  210. * `DelegatingSecurityContextAsyncTaskExecutor`
  211. * `DelegatingSecurityContextTaskExecutor`
  212. * `DelegatingSecurityContextTaskScheduler`