method.adoc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. [[jc-erms]]
  2. = EnableReactiveMethodSecurity
  3. Spring Security supports method security by using https://projectreactor.io/docs/core/release/reference/#context[Reactor's Context], which is set up by `ReactiveSecurityContextHolder`.
  4. The following example shows how to retrieve the currently logged in user's message:
  5. [NOTE]
  6. ====
  7. For this example to work, the return type of the method must be a `org.reactivestreams.Publisher` (that is, a `Mono` or a `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 including Kotlin coroutines.
  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. [tabs]
  257. ======
  258. Java::
  259. +
  260. [source,java,role="primary"]
  261. ----
  262. Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
  263. Mono<String> messageByUsername = ReactiveSecurityContextHolder.getContext()
  264. .map(SecurityContext::getAuthentication)
  265. .map(Authentication::getName)
  266. .flatMap(this::findMessageByUsername)
  267. // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
  268. .contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
  269. StepVerifier.create(messageByUsername)
  270. .expectNext("Hi user")
  271. .verifyComplete();
  272. ----
  273. Kotlin::
  274. +
  275. [source,kotlin,role="secondary"]
  276. ----
  277. val authentication: Authentication = TestingAuthenticationToken("user", "password", "ROLE_USER")
  278. val messageByUsername: Mono<String> = ReactiveSecurityContextHolder.getContext()
  279. .map(SecurityContext::getAuthentication)
  280. .map(Authentication::getName)
  281. .flatMap(this::findMessageByUsername) // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
  282. .contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
  283. StepVerifier.create(messageByUsername)
  284. .expectNext("Hi user")
  285. .verifyComplete()
  286. ----
  287. ======
  288. Where `this::findMessageByUsername` is defined as:
  289. [tabs]
  290. ======
  291. Java::
  292. +
  293. [source,java,role="primary"]
  294. ----
  295. Mono<String> findMessageByUsername(String username) {
  296. return Mono.just("Hi " + username);
  297. }
  298. ----
  299. Kotlin::
  300. +
  301. [source,kotlin,role="secondary"]
  302. ----
  303. fun findMessageByUsername(username: String): Mono<String> {
  304. return Mono.just("Hi $username")
  305. }
  306. ----
  307. ======
  308. The following minimal method security configures method security in reactive applications:
  309. [tabs]
  310. ======
  311. Java::
  312. +
  313. [source,java,role="primary"]
  314. ----
  315. @Configuration
  316. @EnableReactiveMethodSecurity
  317. public class SecurityConfig {
  318. @Bean
  319. public MapReactiveUserDetailsService userDetailsService() {
  320. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  321. UserDetails rob = userBuilder.username("rob")
  322. .password("rob")
  323. .roles("USER")
  324. .build();
  325. UserDetails admin = userBuilder.username("admin")
  326. .password("admin")
  327. .roles("USER","ADMIN")
  328. .build();
  329. return new MapReactiveUserDetailsService(rob, admin);
  330. }
  331. }
  332. ----
  333. Kotlin::
  334. +
  335. [source,kotlin,role="secondary"]
  336. ----
  337. @Configuration
  338. @EnableReactiveMethodSecurity
  339. class SecurityConfig {
  340. @Bean
  341. fun userDetailsService(): MapReactiveUserDetailsService {
  342. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  343. val rob = userBuilder.username("rob")
  344. .password("rob")
  345. .roles("USER")
  346. .build()
  347. val admin = userBuilder.username("admin")
  348. .password("admin")
  349. .roles("USER", "ADMIN")
  350. .build()
  351. return MapReactiveUserDetailsService(rob, admin)
  352. }
  353. }
  354. ----
  355. ======
  356. Consider the following class:
  357. [tabs]
  358. ======
  359. Java::
  360. +
  361. [source,java,role="primary"]
  362. ----
  363. @Component
  364. public class HelloWorldMessageService {
  365. @PreAuthorize("hasRole('ADMIN')")
  366. public Mono<String> findMessage() {
  367. return Mono.just("Hello World!");
  368. }
  369. }
  370. ----
  371. Kotlin::
  372. +
  373. [source,kotlin,role="secondary"]
  374. ----
  375. @Component
  376. class HelloWorldMessageService {
  377. @PreAuthorize("hasRole('ADMIN')")
  378. fun findMessage(): Mono<String> {
  379. return Mono.just("Hello World!")
  380. }
  381. }
  382. ----
  383. ======
  384. Alternatively, the following class uses Kotlin coroutines:
  385. [tabs]
  386. ======
  387. Kotlin::
  388. +
  389. [source,kotlin,role="primary"]
  390. ----
  391. @Component
  392. class HelloWorldMessageService {
  393. @PreAuthorize("hasRole('ADMIN')")
  394. suspend fun findMessage(): String {
  395. delay(10)
  396. return "Hello World!"
  397. }
  398. }
  399. ----
  400. ======
  401. Combined with our configuration above, `@PreAuthorize("hasRole('ADMIN')")` ensures that `findByMessage` is invoked only by a user with the `ADMIN` role.
  402. Note that any of the expressions in standard method security work for `@EnableReactiveMethodSecurity`.
  403. However, at this time, we support only a return type of `Boolean` or `boolean` of the expression.
  404. This means that the expression must not block.
  405. 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:
  406. [tabs]
  407. ======
  408. Java::
  409. +
  410. [source,java,role="primary"]
  411. ----
  412. @Configuration
  413. @EnableWebFluxSecurity
  414. @EnableReactiveMethodSecurity
  415. public class SecurityConfig {
  416. @Bean
  417. SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
  418. return http
  419. // Demonstrate that method security works
  420. // Best practice to use both for defense in depth
  421. .authorizeExchange(exchanges -> exchanges
  422. .anyExchange().permitAll()
  423. )
  424. .httpBasic(withDefaults())
  425. .build();
  426. }
  427. @Bean
  428. MapReactiveUserDetailsService userDetailsService() {
  429. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  430. UserDetails rob = userBuilder.username("rob")
  431. .password("rob")
  432. .roles("USER")
  433. .build();
  434. UserDetails admin = userBuilder.username("admin")
  435. .password("admin")
  436. .roles("USER","ADMIN")
  437. .build();
  438. return new MapReactiveUserDetailsService(rob, admin);
  439. }
  440. }
  441. ----
  442. Kotlin::
  443. +
  444. [source,kotlin,role="secondary"]
  445. ----
  446. @Configuration
  447. @EnableWebFluxSecurity
  448. @EnableReactiveMethodSecurity
  449. class SecurityConfig {
  450. @Bean
  451. open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  452. return http {
  453. authorizeExchange {
  454. authorize(anyExchange, permitAll)
  455. }
  456. httpBasic { }
  457. }
  458. }
  459. @Bean
  460. fun userDetailsService(): MapReactiveUserDetailsService {
  461. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  462. val rob = userBuilder.username("rob")
  463. .password("rob")
  464. .roles("USER")
  465. .build()
  466. val admin = userBuilder.username("admin")
  467. .password("admin")
  468. .roles("USER", "ADMIN")
  469. .build()
  470. return MapReactiveUserDetailsService(rob, admin)
  471. }
  472. }
  473. ----
  474. ======
  475. You can find a complete sample in {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method].