2
0

webflux.adoc 7.3 KB

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