webflux.adoc 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. import org.springframework.security.config.web.server.invoke
  87. @Configuration
  88. @EnableWebFluxSecurity
  89. class HelloWebfluxSecurityConfig {
  90. @Bean
  91. fun userDetailsService(): ReactiveUserDetailsService {
  92. val userDetails = User.withDefaultPasswordEncoder()
  93. .username("user")
  94. .password("user")
  95. .roles("USER")
  96. .build()
  97. return MapReactiveUserDetailsService(userDetails)
  98. }
  99. @Bean
  100. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  101. return http {
  102. authorizeExchange {
  103. authorize(anyExchange, authenticated)
  104. }
  105. formLogin { }
  106. httpBasic { }
  107. }
  108. }
  109. }
  110. -----
  111. ======
  112. [NOTE]
  113. Make sure that you import the `invoke` function in your Kotlin class, sometimes the IDE will not auto-import it causing compilation issues.
  114. This configuration explicitly sets up all the same things as our minimal configuration.
  115. From here you can easily make the changes to the defaults.
  116. 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].
  117. [[jc-webflux-multiple-filter-chains]]
  118. === Multiple Chains Support
  119. You can configure multiple `SecurityWebFilterChain` instances to separate configuration by ``RequestMatcher``s.
  120. For example, you can isolate configuration for URLs that start with `/api`, like so:
  121. [tabs]
  122. ======
  123. Java::
  124. +
  125. [source,java,role="primary"]
  126. ----
  127. @Configuration
  128. @EnableWebFluxSecurity
  129. static class MultiSecurityHttpConfig {
  130. @Order(Ordered.HIGHEST_PRECEDENCE) <1>
  131. @Bean
  132. SecurityWebFilterChain apiHttpSecurity(ServerHttpSecurity http) {
  133. http
  134. .securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**")) <2>
  135. .authorizeExchange((exchanges) -> exchanges
  136. .anyExchange().authenticated()
  137. )
  138. .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt); <3>
  139. return http.build();
  140. }
  141. @Bean
  142. SecurityWebFilterChain webHttpSecurity(ServerHttpSecurity http) { <4>
  143. http
  144. .authorizeExchange((exchanges) -> exchanges
  145. .anyExchange().authenticated()
  146. )
  147. .httpBasic(withDefaults()); <5>
  148. return http.build();
  149. }
  150. @Bean
  151. ReactiveUserDetailsService userDetailsService() {
  152. return new MapReactiveUserDetailsService(
  153. PasswordEncodedUser.user(), PasswordEncodedUser.admin());
  154. }
  155. }
  156. ----
  157. Kotlin::
  158. +
  159. [source,kotlin,role="secondary"]
  160. ----
  161. import org.springframework.security.config.web.server.invoke
  162. @Configuration
  163. @EnableWebFluxSecurity
  164. open class MultiSecurityHttpConfig {
  165. @Order(Ordered.HIGHEST_PRECEDENCE) <1>
  166. @Bean
  167. open fun apiHttpSecurity(http: ServerHttpSecurity): SecurityWebFilterChain {
  168. return http {
  169. securityMatcher(PathPatternParserServerWebExchangeMatcher("/api/**")) <2>
  170. authorizeExchange {
  171. authorize(anyExchange, authenticated)
  172. }
  173. oauth2ResourceServer {
  174. jwt { } <3>
  175. }
  176. }
  177. }
  178. @Bean
  179. open fun webHttpSecurity(http: ServerHttpSecurity): SecurityWebFilterChain { <4>
  180. return http {
  181. authorizeExchange {
  182. authorize(anyExchange, authenticated)
  183. }
  184. httpBasic { } <5>
  185. }
  186. }
  187. @Bean
  188. open fun userDetailsService(): ReactiveUserDetailsService {
  189. return MapReactiveUserDetailsService(
  190. PasswordEncodedUser.user(), PasswordEncodedUser.admin()
  191. )
  192. }
  193. }
  194. ----
  195. ======
  196. <1> Configure a `SecurityWebFilterChain` with an `@Order` to specify which `SecurityWebFilterChain` Spring Security should consider first
  197. <2> Use `PathPatternParserServerWebExchangeMatcher` to state that this `SecurityWebFilterChain` will only apply to URL paths that start with `/api/`
  198. <3> Specify the authentication mechanisms that will be used for `/api/**` endpoints
  199. <4> Create another instance of `SecurityWebFilterChain` with lower precedence to match all other URLs
  200. <5> Specify the authentication mechanisms that will be used for the rest of the application
  201. Spring Security will select one `SecurityWebFilterChain` `@Bean` for each request.
  202. It will match the requests in order by the `securityMatcher` definition.
  203. In this case, that means that if the URL path starts with `/api`, then Spring Security will use `apiHttpSecurity`.
  204. If the URL does not start with `/api` then Spring Security will default to `webHttpSecurity`, which has an implied `securityMatcher` that matches any request.