2
0

webflux.adoc 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. [[jc-webflux]]
  2. = WebFlux Security
  3. Spring Security's WebFlux support relies on a `WebFilter` and works the same for Spring WebFlux and Spring WebFlux.Fn.
  4. You can find a few sample applications that demonstrate the code below:
  5. * Hello WebFlux {gh-samples-url}/reactive/webflux/java/hello-security[hellowebflux]
  6. * Hello WebFlux.Fn {gh-samples-url}/reactive/webflux-fn/hello-security[hellowebfluxfn]
  7. * Hello WebFlux Method {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method]
  8. == Minimal WebFlux Security Configuration
  9. You can find a minimal WebFlux Security configuration below:
  10. .Minimal WebFlux Security Configuration
  11. ====
  12. .Java
  13. [source,java,role="primary"]
  14. -----
  15. @EnableWebFluxSecurity
  16. public class HelloWebfluxSecurityConfig {
  17. @Bean
  18. public MapReactiveUserDetailsService userDetailsService() {
  19. UserDetails user = User.withDefaultPasswordEncoder()
  20. .username("user")
  21. .password("user")
  22. .roles("USER")
  23. .build();
  24. return new MapReactiveUserDetailsService(user);
  25. }
  26. }
  27. -----
  28. .Kotlin
  29. [source,kotlin,role="secondary"]
  30. -----
  31. @EnableWebFluxSecurity
  32. class HelloWebfluxSecurityConfig {
  33. @Bean
  34. fun userDetailsService(): ReactiveUserDetailsService {
  35. val userDetails = User.withDefaultPasswordEncoder()
  36. .username("user")
  37. .password("user")
  38. .roles("USER")
  39. .build()
  40. return MapReactiveUserDetailsService(userDetails)
  41. }
  42. }
  43. -----
  44. ====
  45. This configuration provides form and http basic authentication, sets up authorization to require an authenticated user for accessing any page, sets up a default log in page and a default log out page, sets up security related HTTP headers, CSRF protection, and more.
  46. == Explicit WebFlux Security Configuration
  47. You can find an explicit version of the minimal WebFlux Security configuration below:
  48. .Explicit WebFlux Security Configuration
  49. ====
  50. .Java
  51. [source,java,role="primary"]
  52. -----
  53. @Configuration
  54. @EnableWebFluxSecurity
  55. public class HelloWebfluxSecurityConfig {
  56. @Bean
  57. public MapReactiveUserDetailsService userDetailsService() {
  58. UserDetails user = User.withDefaultPasswordEncoder()
  59. .username("user")
  60. .password("user")
  61. .roles("USER")
  62. .build();
  63. return new MapReactiveUserDetailsService(user);
  64. }
  65. @Bean
  66. public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  67. http
  68. .authorizeExchange(exchanges -> exchanges
  69. .anyExchange().authenticated()
  70. )
  71. .httpBasic(withDefaults())
  72. .formLogin(withDefaults());
  73. return http.build();
  74. }
  75. }
  76. -----
  77. .Kotlin
  78. [source,kotlin,role="secondary"]
  79. -----
  80. @Configuration
  81. @EnableWebFluxSecurity
  82. class HelloWebfluxSecurityConfig {
  83. @Bean
  84. fun userDetailsService(): ReactiveUserDetailsService {
  85. val userDetails = User.withDefaultPasswordEncoder()
  86. .username("user")
  87. .password("user")
  88. .roles("USER")
  89. .build()
  90. return MapReactiveUserDetailsService(userDetails)
  91. }
  92. @Bean
  93. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  94. return http {
  95. authorizeExchange {
  96. authorize(anyExchange, authenticated)
  97. }
  98. formLogin { }
  99. httpBasic { }
  100. }
  101. }
  102. }
  103. -----
  104. ====
  105. This configuration explicitly sets up all the same things as our minimal configuration.
  106. From here you can easily make the changes to the defaults.
  107. You can find more examples of explicit configuration in unit tests, by searching https://github.com/spring-projects/spring-security/search?q=path%3Aconfig%2Fsrc%2Ftest%2F+EnableWebFluxSecurity[EnableWebFluxSecurity in the `config/src/test/` directory].
  108. [[jc-webflux-multiple-filter-chains]]
  109. === Multiple Chains Support
  110. You can configure multiple `SecurityWebFilterChain` instances to separate configuration by ``RequestMatcher``s.
  111. For example, you can isolate configuration for URLs that start with `/api`, like so:
  112. ====
  113. .Java
  114. [source,java,role="primary"]
  115. ----
  116. @Configuration
  117. @EnableWebFluxSecurity
  118. static class MultiSecurityHttpConfig {
  119. @Order(Ordered.HIGHEST_PRECEDENCE) <1>
  120. @Bean
  121. SecurityWebFilterChain apiHttpSecurity(ServerHttpSecurity http) {
  122. http
  123. .securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**")) <2>
  124. .authorizeExchange((exchanges) -> exchanges
  125. .anyExchange().authenticated()
  126. )
  127. .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt); <3>
  128. return http.build();
  129. }
  130. @Bean
  131. SecurityWebFilterChain webHttpSecurity(ServerHttpSecurity http) { <4>
  132. http
  133. .authorizeExchange((exchanges) -> exchanges
  134. .anyExchange().authenticated()
  135. )
  136. .httpBasic(withDefaults()); <5>
  137. return http.build();
  138. }
  139. @Bean
  140. ReactiveUserDetailsService userDetailsService() {
  141. return new MapReactiveUserDetailsService(
  142. PasswordEncodedUser.user(), PasswordEncodedUser.admin());
  143. }
  144. }
  145. ----
  146. .Kotlin
  147. [source,kotlin,role="secondary"]
  148. ----
  149. @Configuration
  150. @EnableWebFluxSecurity
  151. open class MultiSecurityHttpConfig {
  152. @Order(Ordered.HIGHEST_PRECEDENCE) <1>
  153. @Bean
  154. open fun apiHttpSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  155. return http {
  156. securityMatcher(PathPatternParserServerWebExchangeMatcher("/api/**")) <2>
  157. authorizeExchange {
  158. authorize(anyExchange, authenticated)
  159. }
  160. oauth2ResourceServer {
  161. jwt { } <3>
  162. }
  163. }
  164. }
  165. @Bean
  166. open fun webHttpSecurity(http: ServerHttpSecurity): SecurityWebFilterChain { <4>
  167. return http {
  168. authorizeExchange {
  169. authorize(anyExchange, authenticated)
  170. }
  171. httpBasic { } <5>
  172. }
  173. }
  174. @Bean
  175. open fun userDetailsService(): ReactiveUserDetailsService {
  176. return MapReactiveUserDetailsService(
  177. PasswordEncodedUser.user(), PasswordEncodedUser.admin()
  178. )
  179. }
  180. }
  181. ----
  182. ====
  183. <1> Configure a `SecurityWebFilterChain` with an `@Order` to specify which `SecurityWebFilterChain` Spring Security should consider first
  184. <2> Use `PathPatternParserServerWebExchangeMatcher` to state that this `SecurityWebFilterChain` will only apply to URL paths that start with `/api/`
  185. <3> Specify the authentication mechanisms that will be used for `/api/**` endpoints
  186. <4> Create another instance of `SecurityWebFilterChain` with lower precedence to match all other URLs
  187. <5> Specify the authentication mechanisms that will be used for the rest of the application
  188. Spring Security will select one `SecurityWebFilterChain` `@Bean` for each request.
  189. It will match the requests in order by the `securityMatcher` definition.
  190. In this case, that means that if the URL path starts with `/api`, then Spring Security will use `apiHttpSecurity`.
  191. If the URL does not start with `/api` then Spring Security will default to `webHttpSecurity`, which has an implied `securityMatcher` that matches any request.