method.adoc 16 KB

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