method.adoc 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. [[jc-erms]]
  2. = EnableReactiveMethodSecurity
  3. Spring Security supports method security by using https://projectreactor.io/docs/core/release/reference/#context[Reactor's Context], which is set up by `ReactiveSecurityContextHolder`.
  4. The following example shows how to retrieve the currently logged in user's message:
  5. [NOTE]
  6. ====
  7. For this example to work, the return type of the method must be a `org.reactivestreams.Publisher` (that is, a `Mono` or a `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. .contextWrite(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. .contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
  34. StepVerifier.create(messageByUsername)
  35. .expectNext("Hi user")
  36. .verifyComplete()
  37. ----
  38. ====
  39. Where `this::findMessageByUsername` is 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. The following minimal method security configures method security in reactive applications:
  57. ====
  58. .Java
  59. [source,java,role="primary"]
  60. ----
  61. @Configuration
  62. @EnableReactiveMethodSecurity
  63. public class SecurityConfig {
  64. @Bean
  65. public MapReactiveUserDetailsService userDetailsService() {
  66. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  67. UserDetails rob = userBuilder.username("rob")
  68. .password("rob")
  69. .roles("USER")
  70. .build();
  71. UserDetails admin = userBuilder.username("admin")
  72. .password("admin")
  73. .roles("USER","ADMIN")
  74. .build();
  75. return new MapReactiveUserDetailsService(rob, admin);
  76. }
  77. }
  78. ----
  79. .Kotlin
  80. [source,kotlin,role="secondary"]
  81. ----
  82. @Configuration
  83. @EnableReactiveMethodSecurity
  84. class SecurityConfig {
  85. @Bean
  86. fun userDetailsService(): MapReactiveUserDetailsService {
  87. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  88. val rob = userBuilder.username("rob")
  89. .password("rob")
  90. .roles("USER")
  91. .build()
  92. val admin = userBuilder.username("admin")
  93. .password("admin")
  94. .roles("USER", "ADMIN")
  95. .build()
  96. return MapReactiveUserDetailsService(rob, admin)
  97. }
  98. }
  99. ----
  100. ====
  101. Consider the following class:
  102. ====
  103. .Java
  104. [source,java,role="primary"]
  105. ----
  106. @Component
  107. public class HelloWorldMessageService {
  108. @PreAuthorize("hasRole('ADMIN')")
  109. public Mono<String> findMessage() {
  110. return Mono.just("Hello World!");
  111. }
  112. }
  113. ----
  114. .Kotlin
  115. [source,kotlin,role="secondary"]
  116. ----
  117. @Component
  118. class HelloWorldMessageService {
  119. @PreAuthorize("hasRole('ADMIN')")
  120. fun findMessage(): Mono<String> {
  121. return Mono.just("Hello World!")
  122. }
  123. }
  124. ----
  125. ====
  126. Alternatively, the following class uses Kotlin coroutines:
  127. ====
  128. .Kotlin
  129. [source,kotlin,role="primary"]
  130. ----
  131. @Component
  132. class HelloWorldMessageService {
  133. @PreAuthorize("hasRole('ADMIN')")
  134. suspend fun findMessage(): String {
  135. delay(10)
  136. return "Hello World!"
  137. }
  138. }
  139. ----
  140. ====
  141. Combined with our configuration above, `@PreAuthorize("hasRole('ADMIN')")` ensures that `findByMessage` is invoked only by a user with the `ADMIN` role.
  142. Note that any of the expressions in standard method security work for `@EnableReactiveMethodSecurity`.
  143. However, at this time, we support only a return type of `Boolean` or `boolean` of the expression.
  144. This means that the expression must not block.
  145. 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:
  146. ====
  147. .Java
  148. [source,java,role="primary"]
  149. ----
  150. @Configuration
  151. @EnableWebFluxSecurity
  152. @EnableReactiveMethodSecurity
  153. public class SecurityConfig {
  154. @Bean
  155. SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
  156. return http
  157. // Demonstrate that method security works
  158. // Best practice to use both for defense in depth
  159. .authorizeExchange(exchanges -> exchanges
  160. .anyExchange().permitAll()
  161. )
  162. .httpBasic(withDefaults())
  163. .build();
  164. }
  165. @Bean
  166. MapReactiveUserDetailsService userDetailsService() {
  167. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  168. UserDetails rob = userBuilder.username("rob")
  169. .password("rob")
  170. .roles("USER")
  171. .build();
  172. UserDetails admin = userBuilder.username("admin")
  173. .password("admin")
  174. .roles("USER","ADMIN")
  175. .build();
  176. return new MapReactiveUserDetailsService(rob, admin);
  177. }
  178. }
  179. ----
  180. .Kotlin
  181. [source,kotlin,role="secondary"]
  182. ----
  183. @Configuration
  184. @EnableWebFluxSecurity
  185. @EnableReactiveMethodSecurity
  186. class SecurityConfig {
  187. @Bean
  188. open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  189. return http {
  190. authorizeExchange {
  191. authorize(anyExchange, permitAll)
  192. }
  193. httpBasic { }
  194. }
  195. }
  196. @Bean
  197. fun userDetailsService(): MapReactiveUserDetailsService {
  198. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  199. val rob = userBuilder.username("rob")
  200. .password("rob")
  201. .roles("USER")
  202. .build()
  203. val admin = userBuilder.username("admin")
  204. .password("admin")
  205. .roles("USER", "ADMIN")
  206. .build()
  207. return MapReactiveUserDetailsService(rob, admin)
  208. }
  209. }
  210. ----
  211. ====
  212. You can find a complete sample in {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method].