method.adoc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. [[jc-erms]]
  2. = EnableReactiveMethodSecurity
  3. Spring Security supports method security using https://projectreactor.io/docs/core/release/reference/#context[Reactor's Context] which is setup using `ReactiveSecurityContextHolder`.
  4. For example, this demonstrates how to retrieve the currently logged in user's message.
  5. [NOTE]
  6. ====
  7. For this to work the return type of the method must be a `org.reactivestreams.Publisher` (for example, `Mono`/`Flux`).
  8. This is necessary to integrate with Reactor's `Context`.
  9. ====
  10. [[jc-enable-reactive-method-security-authorization-manager]]
  11. == EnableReactiveMethodSecurity with AuthorizationManager
  12. In Spring Security 5.8, we can enable annotation-based security using the `@EnableReactiveMethodSecurity(useAuthorizationManager=true)` annotation on any `@Configuration` instance.
  13. This improves upon `@EnableReactiveMethodSecurity` in a number of ways. `@EnableReactiveMethodSecurity(useAuthorizationManager=true)`:
  14. 1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters.
  15. This simplifies reuse and customization.
  16. 2. Supports reactive return types. Note that we are waiting on https://github.com/spring-projects/spring-framework/issues/22462[additional coroutine support from the Spring Framework] before adding coroutine support.
  17. 3. Is built using native Spring AOP, removing abstractions and allowing you to use Spring AOP building blocks to customize
  18. 4. Checks for conflicting annotations to ensure an unambiguous security configuration
  19. 5. Complies with JSR-250
  20. [NOTE]
  21. ====
  22. For earlier versions, please read about similar support with <<jc-enable-reactive-method-security, @EnableReactiveMethodSecurity>>.
  23. ====
  24. For example, the following would enable Spring Security's `@PreAuthorize` annotation:
  25. .Method Security Configuration
  26. ====
  27. .Java
  28. [source,java,role="primary"]
  29. ----
  30. @EnableReactiveMethodSecurity(useAuthorizationManager=true)
  31. public class MethodSecurityConfig {
  32. // ...
  33. }
  34. ----
  35. ====
  36. Adding an annotation to a method (on a class or interface) would then limit the access to that method accordingly.
  37. Spring Security's native annotation support defines a set of attributes for the method.
  38. These will be passed to the various method interceptors, like `AuthorizationManagerBeforeReactiveMethodInterceptor`, for it to make the actual decision:
  39. .Method Security Annotation Usage
  40. ====
  41. .Java
  42. [source,java,role="primary"]
  43. ----
  44. public interface BankService {
  45. @PreAuthorize("hasRole('USER')")
  46. Mono<Account> readAccount(Long id);
  47. @PreAuthorize("hasRole('USER')")
  48. Flux<Account> findAccounts();
  49. @PreAuthorize("@func.apply(#account)")
  50. Mono<Account> post(Account account, Double amount);
  51. }
  52. ----
  53. ====
  54. In this case `hasRole` refers to the method found in `SecurityExpressionRoot` that gets invoked by the SpEL evaluation engine.
  55. `@bean` refers to a custom component you have defined, where `apply` can return `Boolean` or `Mono<Boolean>` to indicate the authorization decision.
  56. A bean like that might look something like this:
  57. .Method Security Reactive Boolean Expression
  58. ====
  59. .Java
  60. [source,java,role="primary"]
  61. ----
  62. @Bean
  63. public Function<Account, Mono<Boolean>> func() {
  64. return (account) -> Mono.defer(() -> Mono.just(account.getId().equals(12)));
  65. }
  66. ----
  67. ====
  68. === Customizing Authorization
  69. Spring Security's `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` ship with rich expression-based support.
  70. [[jc-reactive-method-security-custom-granted-authority-defaults]]
  71. Also, for role-based authorization, Spring Security adds a default `ROLE_` prefix, which is uses when evaluating expressions like `hasRole`.
  72. You can configure the authorization rules to use a different prefix by exposing a `GrantedAuthorityDefaults` bean, like so:
  73. .Custom MethodSecurityExpressionHandler
  74. ====
  75. .Java
  76. [source,java,role="primary"]
  77. ----
  78. @Bean
  79. static GrantedAuthorityDefaults grantedAuthorityDefaults() {
  80. return new GrantedAuthorityDefaults("MYPREFIX_");
  81. }
  82. ----
  83. ====
  84. [TIP]
  85. ====
  86. We expose `GrantedAuthorityDefaults` using a `static` method to ensure that Spring publishes it before it initializes Spring Security's method security `@Configuration` classes
  87. ====
  88. [[jc-reactive-method-security-custom-authorization-manager]]
  89. === Custom Authorization Managers
  90. Method authorization is a combination of before- and after-method authorization.
  91. [NOTE]
  92. ====
  93. Before-method authorization is performed before the method is invoked.
  94. If that authorization denies access, the method is not invoked, and an `AccessDeniedException` is thrown.
  95. After-method authorization is performed after the method is invoked, but before the method returns to the caller.
  96. If that authorization denies access, the value is not returned, and an `AccessDeniedException` is thrown
  97. ====
  98. To recreate what adding `@EnableReactiveMethodSecurity(useAuthorizationManager=true)` does by default, you would publish the following configuration:
  99. .Full Pre-post Method Security Configuration
  100. ====
  101. .Java
  102. [source,java,role="primary"]
  103. ----
  104. @Configuration
  105. class MethodSecurityConfig {
  106. @Bean
  107. BeanDefinitionRegistryPostProcessor aopConfig() {
  108. return AopConfigUtils::registerAutoProxyCreatorIfNecessary;
  109. }
  110. @Bean
  111. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  112. PreFilterAuthorizationReactiveMethodInterceptor preFilterInterceptor() {
  113. return new PreFilterAuthorizationReactiveMethodInterceptor();
  114. }
  115. @Bean
  116. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  117. AuthorizationManagerBeforeReactiveMethodInterceptor preAuthorizeInterceptor() {
  118. return AuthorizationManagerBeforeReactiveMethodInterceptor.preAuthorize();
  119. }
  120. @Bean
  121. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  122. AuthorizationManagerAfterReactiveMethodInterceptor postAuthorizeInterceptor() {
  123. return AuthorizationManagerAfterReactiveMethodInterceptor.postAuthorize();
  124. }
  125. @Bean
  126. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  127. PostFilterAuthorizationReactiveMethodInterceptor postFilterInterceptor() {
  128. return new PostFilterAuthorizationReactiveMethodInterceptor();
  129. }
  130. }
  131. ----
  132. ====
  133. Notice that Spring Security's method security is built using Spring AOP.
  134. So, interceptors are invoked based on the order specified.
  135. This can be customized by calling `setOrder` on the interceptor instances like so:
  136. .Publish Custom Advisor
  137. ====
  138. .Java
  139. [source,java,role="primary"]
  140. ----
  141. @Bean
  142. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  143. Advisor postFilterAuthorizationMethodInterceptor() {
  144. PostFilterAuthorizationMethodInterceptor interceptor = new PostFilterAuthorizationReactiveMethodInterceptor();
  145. interceptor.setOrder(AuthorizationInterceptorOrders.POST_AUTHORIZE.getOrder() - 1);
  146. return interceptor;
  147. }
  148. ----
  149. ====
  150. You may want to only support `@PreAuthorize` in your application, in which case you can do the following:
  151. .Only @PreAuthorize Configuration
  152. ====
  153. .Java
  154. [source,java,role="primary"]
  155. ----
  156. @Configuration
  157. class MethodSecurityConfig {
  158. @Bean
  159. BeanDefinitionRegistryPostProcessor aopConfig() {
  160. return AopConfigUtils::registerAutoProxyCreatorIfNecessary;
  161. }
  162. @Bean
  163. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  164. Advisor preAuthorize() {
  165. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
  166. }
  167. }
  168. ----
  169. ====
  170. Or, you may have a custom before-method `ReactiveAuthorizationManager` that you want to add to the list.
  171. In this case, you will need to tell Spring Security both the `ReactiveAuthorizationManager` and to which methods and classes your authorization manager applies.
  172. Thus, you can configure Spring Security to invoke your `ReactiveAuthorizationManager` in between `@PreAuthorize` and `@PostAuthorize` like so:
  173. .Custom Before Advisor
  174. ====
  175. .Java
  176. [source,java,role="primary"]
  177. ----
  178. @EnableReactiveMethodSecurity(useAuthorizationManager=true)
  179. class MethodSecurityConfig {
  180. @Bean
  181. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  182. public Advisor customAuthorize() {
  183. JdkRegexpMethodPointcut pattern = new JdkRegexpMethodPointcut();
  184. pattern.setPattern("org.mycompany.myapp.service.*");
  185. ReactiveAuthorizationManager<MethodInvocation> rule = AuthorityAuthorizationManager.isAuthenticated();
  186. AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(pattern, rule);
  187. interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  188. return interceptor;
  189. }
  190. }
  191. ----
  192. ====
  193. [TIP]
  194. ====
  195. You can place your interceptor in between Spring Security method interceptors using the order constants specified in `AuthorizationInterceptorsOrder`.
  196. ====
  197. The same can be done for after-method authorization.
  198. After-method authorization is generally concerned with analysing the return value to verify access.
  199. For example, you might have a method that confirms that the account requested actually belongs to the logged-in user like so:
  200. .@PostAuthorize example
  201. ====
  202. .Java
  203. [source,java,role="primary"]
  204. ----
  205. public interface BankService {
  206. @PreAuthorize("hasRole('USER')")
  207. @PostAuthorize("returnObject.owner == authentication.name")
  208. Mono<Account> readAccount(Long id);
  209. }
  210. ----
  211. ====
  212. You can supply your own `AuthorizationMethodInterceptor` to customize how access to the return value is evaluated.
  213. For example, if you have your own custom annotation, you can configure it like so:
  214. .Custom After Advisor
  215. ====
  216. .Java
  217. [source,java,role="primary"]
  218. ----
  219. @EnableReactiveMethodSecurity(useAuthorizationManager=true)
  220. class MethodSecurityConfig {
  221. @Bean
  222. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  223. public Advisor customAuthorize(ReactiveAuthorizationManager<MethodInvocationResult> rules) {
  224. AnnotationMethodMatcher pattern = new AnnotationMethodMatcher(MySecurityAnnotation.class);
  225. AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(pattern, rules);
  226. interceptor.setOrder(AuthorizationInterceptorsOrder.POST_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  227. return interceptor;
  228. }
  229. }
  230. ----
  231. ====
  232. and it will be invoked after the `@PostAuthorize` interceptor.
  233. == EnableReactiveMethodSecurity
  234. [WARNING]
  235. ====
  236. `@EnableReactiveMethodSecurity` also supports Kotlin coroutines, though only to a limited degree.
  237. When intercepting coroutines, only the first interceptor participates.
  238. If any other interceptors are present and come after Spring Security's method security interceptor, https://github.com/spring-projects/spring-framework/issues/22462[they will be skipped].
  239. ====
  240. ====
  241. .Java
  242. [source,java,role="primary"]
  243. ----
  244. Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
  245. Mono<String> messageByUsername = ReactiveSecurityContextHolder.getContext()
  246. .map(SecurityContext::getAuthentication)
  247. .map(Authentication::getName)
  248. .flatMap(this::findMessageByUsername)
  249. // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
  250. .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
  251. StepVerifier.create(messageByUsername)
  252. .expectNext("Hi user")
  253. .verifyComplete();
  254. ----
  255. .Kotlin
  256. [source,kotlin,role="secondary"]
  257. ----
  258. val authentication: Authentication = TestingAuthenticationToken("user", "password", "ROLE_USER")
  259. val messageByUsername: Mono<String> = ReactiveSecurityContextHolder.getContext()
  260. .map(SecurityContext::getAuthentication)
  261. .map(Authentication::getName)
  262. .flatMap(this::findMessageByUsername) // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
  263. .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication))
  264. StepVerifier.create(messageByUsername)
  265. .expectNext("Hi user")
  266. .verifyComplete()
  267. ----
  268. ====
  269. with `this::findMessageByUsername` defined as:
  270. ====
  271. .Java
  272. [source,java,role="primary"]
  273. ----
  274. Mono<String> findMessageByUsername(String username) {
  275. return Mono.just("Hi " + username);
  276. }
  277. ----
  278. .Kotlin
  279. [source,kotlin,role="secondary"]
  280. ----
  281. fun findMessageByUsername(username: String): Mono<String> {
  282. return Mono.just("Hi $username")
  283. }
  284. ----
  285. ====
  286. Below is a minimal method security configuration when using method security in reactive applications.
  287. ====
  288. .Java
  289. [source,java,role="primary"]
  290. ----
  291. @EnableReactiveMethodSecurity
  292. public class SecurityConfig {
  293. @Bean
  294. public MapReactiveUserDetailsService userDetailsService() {
  295. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  296. UserDetails rob = userBuilder.username("rob")
  297. .password("rob")
  298. .roles("USER")
  299. .build();
  300. UserDetails admin = userBuilder.username("admin")
  301. .password("admin")
  302. .roles("USER","ADMIN")
  303. .build();
  304. return new MapReactiveUserDetailsService(rob, admin);
  305. }
  306. }
  307. ----
  308. .Kotlin
  309. [source,kotlin,role="secondary"]
  310. ----
  311. @EnableReactiveMethodSecurity
  312. class SecurityConfig {
  313. @Bean
  314. fun userDetailsService(): MapReactiveUserDetailsService {
  315. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  316. val rob = userBuilder.username("rob")
  317. .password("rob")
  318. .roles("USER")
  319. .build()
  320. val admin = userBuilder.username("admin")
  321. .password("admin")
  322. .roles("USER", "ADMIN")
  323. .build()
  324. return MapReactiveUserDetailsService(rob, admin)
  325. }
  326. }
  327. ----
  328. ====
  329. Consider the following class:
  330. ====
  331. .Java
  332. [source,java,role="primary"]
  333. ----
  334. @Component
  335. public class HelloWorldMessageService {
  336. @PreAuthorize("hasRole('ADMIN')")
  337. public Mono<String> findMessage() {
  338. return Mono.just("Hello World!");
  339. }
  340. }
  341. ----
  342. .Kotlin
  343. [source,kotlin,role="secondary"]
  344. ----
  345. @Component
  346. class HelloWorldMessageService {
  347. @PreAuthorize("hasRole('ADMIN')")
  348. fun findMessage(): Mono<String> {
  349. return Mono.just("Hello World!")
  350. }
  351. }
  352. ----
  353. ====
  354. Or, the following class using Kotlin coroutines:
  355. ====
  356. .Kotlin
  357. [source,kotlin,role="primary"]
  358. ----
  359. @Component
  360. class HelloWorldMessageService {
  361. @PreAuthorize("hasRole('ADMIN')")
  362. suspend fun findMessage(): String {
  363. delay(10)
  364. return "Hello World!"
  365. }
  366. }
  367. ----
  368. ====
  369. Combined with our configuration above, `@PreAuthorize("hasRole('ADMIN')")` will ensure that `findByMessage` is only invoked by a user with the role `ADMIN`.
  370. It is important to note that any of the expressions in standard method security work for `@EnableReactiveMethodSecurity`.
  371. However, at this time we only support return type of `Boolean` or `boolean` of the expression.
  372. This means that the expression must not block.
  373. 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.
  374. ====
  375. .Java
  376. [source,java,role="primary"]
  377. ----
  378. @EnableWebFluxSecurity
  379. @EnableReactiveMethodSecurity
  380. public class SecurityConfig {
  381. @Bean
  382. SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
  383. return http
  384. // Demonstrate that method security works
  385. // Best practice to use both for defense in depth
  386. .authorizeExchange(exchanges -> exchanges
  387. .anyExchange().permitAll()
  388. )
  389. .httpBasic(withDefaults())
  390. .build();
  391. }
  392. @Bean
  393. MapReactiveUserDetailsService userDetailsService() {
  394. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  395. UserDetails rob = userBuilder.username("rob")
  396. .password("rob")
  397. .roles("USER")
  398. .build();
  399. UserDetails admin = userBuilder.username("admin")
  400. .password("admin")
  401. .roles("USER","ADMIN")
  402. .build();
  403. return new MapReactiveUserDetailsService(rob, admin);
  404. }
  405. }
  406. ----
  407. .Kotlin
  408. [source,kotlin,role="secondary"]
  409. ----
  410. @EnableWebFluxSecurity
  411. @EnableReactiveMethodSecurity
  412. class SecurityConfig {
  413. @Bean
  414. open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  415. return http {
  416. authorizeExchange {
  417. authorize(anyExchange, permitAll)
  418. }
  419. httpBasic { }
  420. }
  421. }
  422. @Bean
  423. fun userDetailsService(): MapReactiveUserDetailsService {
  424. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  425. val rob = userBuilder.username("rob")
  426. .password("rob")
  427. .roles("USER")
  428. .build()
  429. val admin = userBuilder.username("admin")
  430. .password("admin")
  431. .roles("USER", "ADMIN")
  432. .build()
  433. return MapReactiveUserDetailsService(rob, admin)
  434. }
  435. }
  436. ----
  437. ====
  438. You can find a complete sample in {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method]