webflux.adoc 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. A few sample applications demonstrate the code:
  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. The following listing shows a minimal WebFlux Security configuration:
  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 login page and a default logout page, sets up security related HTTP headers, adds CSRF protection, and more.
  46. == Explicit WebFlux Security Configuration
  47. The following page shows an explicit version of the minimal WebFlux Security configuration:
  48. .Explicit WebFlux Security Configuration
  49. ====
  50. .Java
  51. [source,java,role="primary"]
  52. -----
  53. @EnableWebFluxSecurity
  54. public class HelloWebfluxSecurityConfig {
  55. @Bean
  56. public MapReactiveUserDetailsService userDetailsService() {
  57. UserDetails user = User.withDefaultPasswordEncoder()
  58. .username("user")
  59. .password("user")
  60. .roles("USER")
  61. .build();
  62. return new MapReactiveUserDetailsService(user);
  63. }
  64. @Bean
  65. public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  66. http
  67. .authorizeExchange(exchanges -> exchanges
  68. .anyExchange().authenticated()
  69. )
  70. .httpBasic(withDefaults())
  71. .formLogin(withDefaults());
  72. return http.build();
  73. }
  74. }
  75. -----
  76. .Kotlin
  77. [source,kotlin,role="secondary"]
  78. -----
  79. @EnableWebFluxSecurity
  80. class HelloWebfluxSecurityConfig {
  81. @Bean
  82. fun userDetailsService(): ReactiveUserDetailsService {
  83. val userDetails = User.withDefaultPasswordEncoder()
  84. .username("user")
  85. .password("user")
  86. .roles("USER")
  87. .build()
  88. return MapReactiveUserDetailsService(userDetails)
  89. }
  90. @Bean
  91. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  92. return http {
  93. authorizeExchange {
  94. authorize(anyExchange, authenticated)
  95. }
  96. formLogin { }
  97. httpBasic { }
  98. }
  99. }
  100. }
  101. -----
  102. ====
  103. This configuration explicitly sets up all the same things as our minimal configuration.
  104. From here, you can more easily make changes to the defaults.
  105. You can find more examples of explicit configuration in unit tests, by searching for https://github.com/spring-projects/spring-security/search?q=path%3Aconfig%2Fsrc%2Ftest%2F+EnableWebFluxSecurity[`EnableWebFluxSecurity` in the `config/src/test/` directory].
  106. [[jc-webflux-multiple-filter-chains]]
  107. === Multiple Chains Support
  108. You can configure multiple `SecurityWebFilterChain` instances to separate configuration by `RequestMatcher` instances.
  109. For example, you can isolate configuration for URLs that start with `/api`:
  110. ====
  111. .Java
  112. [source,java,role="primary"]
  113. ----
  114. @EnableWebFluxSecurity
  115. static class MultiSecurityHttpConfig {
  116. @Order(Ordered.HIGHEST_PRECEDENCE) <1>
  117. @Bean
  118. SecurityWebFilterChain apiHttpSecurity(ServerHttpSecurity http) {
  119. http
  120. .securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**")) <2>
  121. .authorizeExchange((exchanges) -> exchanges
  122. .anyExchange().authenticated()
  123. )
  124. .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt); <3>
  125. return http.build();
  126. }
  127. @Bean
  128. SecurityWebFilterChain webHttpSecurity(ServerHttpSecurity http) { <4>
  129. http
  130. .authorizeExchange((exchanges) -> exchanges
  131. .anyExchange().authenticated()
  132. )
  133. .httpBasic(withDefaults()); <5>
  134. return http.build();
  135. }
  136. @Bean
  137. ReactiveUserDetailsService userDetailsService() {
  138. return new MapReactiveUserDetailsService(
  139. PasswordEncodedUser.user(), PasswordEncodedUser.admin());
  140. }
  141. }
  142. ----
  143. .Kotlin
  144. [source,kotlin,role="secondary"]
  145. ----
  146. @EnableWebFluxSecurity
  147. open class MultiSecurityHttpConfig {
  148. @Order(Ordered.HIGHEST_PRECEDENCE) <1>
  149. @Bean
  150. open fun apiHttpSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  151. return http {
  152. securityMatcher(PathPatternParserServerWebExchangeMatcher("/api/**")) <2>
  153. authorizeExchange {
  154. authorize(anyExchange, authenticated)
  155. }
  156. oauth2ResourceServer {
  157. jwt { } <3>
  158. }
  159. }
  160. }
  161. @Bean
  162. open fun webHttpSecurity(http: ServerHttpSecurity): SecurityWebFilterChain { <4>
  163. return http {
  164. authorizeExchange {
  165. authorize(anyExchange, authenticated)
  166. }
  167. httpBasic { } <5>
  168. }
  169. }
  170. @Bean
  171. open fun userDetailsService(): ReactiveUserDetailsService {
  172. return MapReactiveUserDetailsService(
  173. PasswordEncodedUser.user(), PasswordEncodedUser.admin()
  174. )
  175. }
  176. }
  177. ----
  178. <1> Configure a `SecurityWebFilterChain` with an `@Order` to specify which `SecurityWebFilterChain` Spring Security should consider first
  179. <2> Use `PathPatternParserServerWebExchangeMatcher` to state that this `SecurityWebFilterChain` will only apply to URL paths that start with `/api/`
  180. <3> Specify the authentication mechanisms that will be used for `/api/**` endpoints
  181. <4> Create another instance of `SecurityWebFilterChain` with lower precedence to match all other URLs
  182. <5> Specify the authentication mechanisms that will be used for the rest of the application
  183. ====
  184. Spring Security selects one `SecurityWebFilterChain` `@Bean` for each request.
  185. It matches the requests in order by the `securityMatcher` definition.
  186. In this case, that means that, if the URL path starts with `/api`, Spring Security uses `apiHttpSecurity`.
  187. If the URL does not start with `/api`, Spring Security defaults to `webHttpSecurity`, which has an implied `securityMatcher` that matches any request.