method.adoc 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. [[jc-erms]]
  2. = EnableReactiveMethodSecurity
  3. Spring Security supports method security using https://projectreactor.io/docs/core/release/reference/#context[Reactor's Context] which is setup using `ReactiveSecurityContextHolder`.
  4. For example, this demonstrates how to retrieve the currently logged in user's message.
  5. [NOTE]
  6. ====
  7. For this to work the return type of the method must be a `org.reactivestreams.Publisher` (i.e. `Mono`/`Flux`) or the function must be a Kotlin coroutine function.
  8. This is necessary to integrate with Reactor's `Context`.
  9. ====
  10. ====
  11. .Java
  12. [source,java,role="primary"]
  13. ----
  14. Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
  15. Mono<String> messageByUsername = ReactiveSecurityContextHolder.getContext()
  16. .map(SecurityContext::getAuthentication)
  17. .map(Authentication::getName)
  18. .flatMap(this::findMessageByUsername)
  19. // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
  20. .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
  21. StepVerifier.create(messageByUsername)
  22. .expectNext("Hi user")
  23. .verifyComplete();
  24. ----
  25. .Kotlin
  26. [source,kotlin,role="secondary"]
  27. ----
  28. val authentication: Authentication = TestingAuthenticationToken("user", "password", "ROLE_USER")
  29. val messageByUsername: Mono<String> = ReactiveSecurityContextHolder.getContext()
  30. .map(SecurityContext::getAuthentication)
  31. .map(Authentication::getName)
  32. .flatMap(this::findMessageByUsername) // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
  33. .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication))
  34. StepVerifier.create(messageByUsername)
  35. .expectNext("Hi user")
  36. .verifyComplete()
  37. ----
  38. ====
  39. with `this::findMessageByUsername` defined as:
  40. ====
  41. .Java
  42. [source,java,role="primary"]
  43. ----
  44. Mono<String> findMessageByUsername(String username) {
  45. return Mono.just("Hi " + username);
  46. }
  47. ----
  48. .Kotlin
  49. [source,kotlin,role="secondary"]
  50. ----
  51. fun findMessageByUsername(username: String): Mono<String> {
  52. return Mono.just("Hi $username")
  53. }
  54. ----
  55. ====
  56. Below is a minimal method security configuration when using method security in reactive applications.
  57. ====
  58. .Java
  59. [source,java,role="primary"]
  60. ----
  61. @EnableReactiveMethodSecurity
  62. public class SecurityConfig {
  63. @Bean
  64. public MapReactiveUserDetailsService userDetailsService() {
  65. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  66. UserDetails rob = userBuilder.username("rob")
  67. .password("rob")
  68. .roles("USER")
  69. .build();
  70. UserDetails admin = userBuilder.username("admin")
  71. .password("admin")
  72. .roles("USER","ADMIN")
  73. .build();
  74. return new MapReactiveUserDetailsService(rob, admin);
  75. }
  76. }
  77. ----
  78. .Kotlin
  79. [source,kotlin,role="secondary"]
  80. ----
  81. @EnableReactiveMethodSecurity
  82. class SecurityConfig {
  83. @Bean
  84. fun userDetailsService(): MapReactiveUserDetailsService {
  85. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  86. val rob = userBuilder.username("rob")
  87. .password("rob")
  88. .roles("USER")
  89. .build()
  90. val admin = userBuilder.username("admin")
  91. .password("admin")
  92. .roles("USER", "ADMIN")
  93. .build()
  94. return MapReactiveUserDetailsService(rob, admin)
  95. }
  96. }
  97. ----
  98. ====
  99. Consider the following class:
  100. ====
  101. .Java
  102. [source,java,role="primary"]
  103. ----
  104. @Component
  105. public class HelloWorldMessageService {
  106. @PreAuthorize("hasRole('ADMIN')")
  107. public Mono<String> findMessage() {
  108. return Mono.just("Hello World!");
  109. }
  110. }
  111. ----
  112. .Kotlin
  113. [source,kotlin,role="secondary"]
  114. ----
  115. @Component
  116. class HelloWorldMessageService {
  117. @PreAuthorize("hasRole('ADMIN')")
  118. fun findMessage(): Mono<String> {
  119. return Mono.just("Hello World!")
  120. }
  121. }
  122. ----
  123. ====
  124. Or, the following class using Kotlin coroutines:
  125. ====
  126. .Kotlin
  127. [source,kotlin,role="primary"]
  128. ----
  129. @Component
  130. class HelloWorldMessageService {
  131. @PreAuthorize("hasRole('ADMIN')")
  132. suspend fun findMessage(): String {
  133. delay(10)
  134. return "Hello World!"
  135. }
  136. }
  137. ----
  138. ====
  139. Combined with our configuration above, `@PreAuthorize("hasRole('ADMIN')")` will ensure that `findByMessage` is only invoked by a user with the role `ADMIN`.
  140. It is important to note that any of the expressions in standard method security work for `@EnableReactiveMethodSecurity`.
  141. However, at this time we only support return type of `Boolean` or `boolean` of the expression.
  142. This means that the expression must not block.
  143. When integrating with xref:reactive/configuration/webflux.adoc#jc-webflux[WebFlux Security], the Reactor Context is automatically established by Spring Security according to the authenticated user.
  144. ====
  145. .Java
  146. [source,java,role="primary"]
  147. ----
  148. @EnableWebFluxSecurity
  149. @EnableReactiveMethodSecurity
  150. public class SecurityConfig {
  151. @Bean
  152. SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
  153. return http
  154. // Demonstrate that method security works
  155. // Best practice to use both for defense in depth
  156. .authorizeExchange(exchanges -> exchanges
  157. .anyExchange().permitAll()
  158. )
  159. .httpBasic(withDefaults())
  160. .build();
  161. }
  162. @Bean
  163. MapReactiveUserDetailsService userDetailsService() {
  164. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  165. UserDetails rob = userBuilder.username("rob")
  166. .password("rob")
  167. .roles("USER")
  168. .build();
  169. UserDetails admin = userBuilder.username("admin")
  170. .password("admin")
  171. .roles("USER","ADMIN")
  172. .build();
  173. return new MapReactiveUserDetailsService(rob, admin);
  174. }
  175. }
  176. ----
  177. .Kotlin
  178. [source,kotlin,role="secondary"]
  179. ----
  180. @EnableWebFluxSecurity
  181. @EnableReactiveMethodSecurity
  182. class SecurityConfig {
  183. @Bean
  184. open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  185. return http {
  186. authorizeExchange {
  187. authorize(anyExchange, permitAll)
  188. }
  189. httpBasic { }
  190. }
  191. }
  192. @Bean
  193. fun userDetailsService(): MapReactiveUserDetailsService {
  194. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  195. val rob = userBuilder.username("rob")
  196. .password("rob")
  197. .roles("USER")
  198. .build()
  199. val admin = userBuilder.username("admin")
  200. .password("admin")
  201. .roles("USER", "ADMIN")
  202. .build()
  203. return MapReactiveUserDetailsService(rob, admin)
  204. }
  205. }
  206. ----
  207. ====
  208. You can find a complete sample in {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method]