method.adoc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. 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. static GrantedAuthorityDefaults grantedAuthorityDefaults() {
  88. return new GrantedAuthorityDefaults("MYPREFIX_");
  89. }
  90. ----
  91. ======
  92. [TIP]
  93. ====
  94. We expose `GrantedAuthorityDefaults` using a `static` method to ensure that Spring publishes it before it initializes Spring Security's method security `@Configuration` classes
  95. ====
  96. [[jc-reactive-method-security-custom-authorization-manager]]
  97. === Custom Authorization Managers
  98. Method authorization is a combination of before- and after-method authorization.
  99. [NOTE]
  100. ====
  101. Before-method authorization is performed before the method is invoked.
  102. If that authorization denies access, the method is not invoked, and an `AccessDeniedException` is thrown.
  103. After-method authorization is performed after the method is invoked, but before the method returns to the caller.
  104. If that authorization denies access, the value is not returned, and an `AccessDeniedException` is thrown
  105. ====
  106. To recreate what adding `@EnableReactiveMethodSecurity(useAuthorizationManager=true)` does by default, you would publish the following configuration:
  107. .Full Pre-post Method Security Configuration
  108. [tabs]
  109. ======
  110. Java::
  111. +
  112. [source,java,role="primary"]
  113. ----
  114. @Configuration
  115. class MethodSecurityConfig {
  116. @Bean
  117. BeanDefinitionRegistryPostProcessor aopConfig() {
  118. return AopConfigUtils::registerAutoProxyCreatorIfNecessary;
  119. }
  120. @Bean
  121. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  122. PreFilterAuthorizationReactiveMethodInterceptor preFilterInterceptor() {
  123. return new PreFilterAuthorizationReactiveMethodInterceptor();
  124. }
  125. @Bean
  126. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  127. AuthorizationManagerBeforeReactiveMethodInterceptor preAuthorizeInterceptor() {
  128. return AuthorizationManagerBeforeReactiveMethodInterceptor.preAuthorize();
  129. }
  130. @Bean
  131. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  132. AuthorizationManagerAfterReactiveMethodInterceptor postAuthorizeInterceptor() {
  133. return AuthorizationManagerAfterReactiveMethodInterceptor.postAuthorize();
  134. }
  135. @Bean
  136. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  137. PostFilterAuthorizationReactiveMethodInterceptor postFilterInterceptor() {
  138. return new PostFilterAuthorizationReactiveMethodInterceptor();
  139. }
  140. }
  141. ----
  142. ======
  143. Notice that Spring Security's method security is built using Spring AOP.
  144. So, interceptors are invoked based on the order specified.
  145. This can be customized by calling `setOrder` on the interceptor instances like so:
  146. .Publish Custom Advisor
  147. [tabs]
  148. ======
  149. Java::
  150. +
  151. [source,java,role="primary"]
  152. ----
  153. @Bean
  154. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  155. Advisor postFilterAuthorizationMethodInterceptor() {
  156. PostFilterAuthorizationMethodInterceptor interceptor = new PostFilterAuthorizationReactiveMethodInterceptor();
  157. interceptor.setOrder(AuthorizationInterceptorOrders.POST_AUTHORIZE.getOrder() - 1);
  158. return interceptor;
  159. }
  160. ----
  161. ======
  162. You may want to only support `@PreAuthorize` in your application, in which case you can do the following:
  163. .Only @PreAuthorize Configuration
  164. [tabs]
  165. ======
  166. Java::
  167. +
  168. [source,java,role="primary"]
  169. ----
  170. @Configuration
  171. class MethodSecurityConfig {
  172. @Bean
  173. BeanDefinitionRegistryPostProcessor aopConfig() {
  174. return AopConfigUtils::registerAutoProxyCreatorIfNecessary;
  175. }
  176. @Bean
  177. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  178. Advisor preAuthorize() {
  179. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
  180. }
  181. }
  182. ----
  183. ======
  184. Or, you may have a custom before-method `ReactiveAuthorizationManager` that you want to add to the list.
  185. In this case, you will need to tell Spring Security both the `ReactiveAuthorizationManager` and to which methods and classes your authorization manager applies.
  186. Thus, you can configure Spring Security to invoke your `ReactiveAuthorizationManager` in between `@PreAuthorize` and `@PostAuthorize` like so:
  187. .Custom Before Advisor
  188. [tabs]
  189. ======
  190. Java::
  191. +
  192. [source,java,role="primary"]
  193. ----
  194. @EnableReactiveMethodSecurity(useAuthorizationManager=true)
  195. class MethodSecurityConfig {
  196. @Bean
  197. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  198. public Advisor customAuthorize() {
  199. JdkRegexpMethodPointcut pattern = new JdkRegexpMethodPointcut();
  200. pattern.setPattern("org.mycompany.myapp.service.*");
  201. ReactiveAuthorizationManager<MethodInvocation> rule = AuthorityAuthorizationManager.isAuthenticated();
  202. AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(pattern, rule);
  203. interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  204. return interceptor;
  205. }
  206. }
  207. ----
  208. ======
  209. [TIP]
  210. ====
  211. You can place your interceptor in between Spring Security method interceptors using the order constants specified in `AuthorizationInterceptorsOrder`.
  212. ====
  213. The same can be done for after-method authorization.
  214. After-method authorization is generally concerned with analysing the return value to verify access.
  215. For example, you might have a method that confirms that the account requested actually belongs to the logged-in user like so:
  216. .@PostAuthorize example
  217. [tabs]
  218. ======
  219. Java::
  220. +
  221. [source,java,role="primary"]
  222. ----
  223. public interface BankService {
  224. @PreAuthorize("hasRole('USER')")
  225. @PostAuthorize("returnObject.owner == authentication.name")
  226. Mono<Account> readAccount(Long id);
  227. }
  228. ----
  229. ======
  230. You can supply your own `AuthorizationMethodInterceptor` to customize how access to the return value is evaluated.
  231. For example, if you have your own custom annotation, you can configure it like so:
  232. .Custom After Advisor
  233. [tabs]
  234. ======
  235. Java::
  236. +
  237. [source,java,role="primary"]
  238. ----
  239. @EnableReactiveMethodSecurity(useAuthorizationManager=true)
  240. class MethodSecurityConfig {
  241. @Bean
  242. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  243. public Advisor customAuthorize(ReactiveAuthorizationManager<MethodInvocationResult> rules) {
  244. AnnotationMethodMatcher pattern = new AnnotationMethodMatcher(MySecurityAnnotation.class);
  245. AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(pattern, rules);
  246. interceptor.setOrder(AuthorizationInterceptorsOrder.POST_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  247. return interceptor;
  248. }
  249. }
  250. ----
  251. ======
  252. and it will be invoked after the `@PostAuthorize` interceptor.
  253. == EnableReactiveMethodSecurity
  254. [WARNING]
  255. ====
  256. `@EnableReactiveMethodSecurity` also supports Kotlin coroutines, though only to a limited degree.
  257. When intercepting coroutines, only the first interceptor participates.
  258. 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].
  259. ====
  260. [tabs]
  261. ======
  262. Java::
  263. +
  264. [source,java,role="primary"]
  265. ----
  266. Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
  267. Mono<String> messageByUsername = ReactiveSecurityContextHolder.getContext()
  268. .map(SecurityContext::getAuthentication)
  269. .map(Authentication::getName)
  270. .flatMap(this::findMessageByUsername)
  271. // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
  272. .contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
  273. StepVerifier.create(messageByUsername)
  274. .expectNext("Hi user")
  275. .verifyComplete();
  276. ----
  277. Kotlin::
  278. +
  279. [source,kotlin,role="secondary"]
  280. ----
  281. val authentication: Authentication = TestingAuthenticationToken("user", "password", "ROLE_USER")
  282. val messageByUsername: Mono<String> = ReactiveSecurityContextHolder.getContext()
  283. .map(SecurityContext::getAuthentication)
  284. .map(Authentication::getName)
  285. .flatMap(this::findMessageByUsername) // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
  286. .contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
  287. StepVerifier.create(messageByUsername)
  288. .expectNext("Hi user")
  289. .verifyComplete()
  290. ----
  291. ======
  292. Where `this::findMessageByUsername` is defined as:
  293. [tabs]
  294. ======
  295. Java::
  296. +
  297. [source,java,role="primary"]
  298. ----
  299. Mono<String> findMessageByUsername(String username) {
  300. return Mono.just("Hi " + username);
  301. }
  302. ----
  303. Kotlin::
  304. +
  305. [source,kotlin,role="secondary"]
  306. ----
  307. fun findMessageByUsername(username: String): Mono<String> {
  308. return Mono.just("Hi $username")
  309. }
  310. ----
  311. ======
  312. The following minimal method security configures method security in reactive applications:
  313. [tabs]
  314. ======
  315. Java::
  316. +
  317. [source,java,role="primary"]
  318. ----
  319. @Configuration
  320. @EnableReactiveMethodSecurity
  321. public class SecurityConfig {
  322. @Bean
  323. public MapReactiveUserDetailsService userDetailsService() {
  324. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  325. UserDetails rob = userBuilder.username("rob")
  326. .password("rob")
  327. .roles("USER")
  328. .build();
  329. UserDetails admin = userBuilder.username("admin")
  330. .password("admin")
  331. .roles("USER","ADMIN")
  332. .build();
  333. return new MapReactiveUserDetailsService(rob, admin);
  334. }
  335. }
  336. ----
  337. Kotlin::
  338. +
  339. [source,kotlin,role="secondary"]
  340. ----
  341. @Configuration
  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. Alternatively, the following class uses 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')")` ensures that `findByMessage` is invoked only by a user with the `ADMIN` role.
  406. Note that any of the expressions in standard method security work for `@EnableReactiveMethodSecurity`.
  407. However, at this time, we support only a 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. @Configuration
  417. @EnableWebFluxSecurity
  418. @EnableReactiveMethodSecurity
  419. public class SecurityConfig {
  420. @Bean
  421. SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
  422. return http
  423. // Demonstrate that method security works
  424. // Best practice to use both for defense in depth
  425. .authorizeExchange(exchanges -> exchanges
  426. .anyExchange().permitAll()
  427. )
  428. .httpBasic(withDefaults())
  429. .build();
  430. }
  431. @Bean
  432. MapReactiveUserDetailsService userDetailsService() {
  433. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  434. UserDetails rob = userBuilder.username("rob")
  435. .password("rob")
  436. .roles("USER")
  437. .build();
  438. UserDetails admin = userBuilder.username("admin")
  439. .password("admin")
  440. .roles("USER","ADMIN")
  441. .build();
  442. return new MapReactiveUserDetailsService(rob, admin);
  443. }
  444. }
  445. ----
  446. Kotlin::
  447. +
  448. [source,kotlin,role="secondary"]
  449. ----
  450. @Configuration
  451. @EnableWebFluxSecurity
  452. @EnableReactiveMethodSecurity
  453. class SecurityConfig {
  454. @Bean
  455. open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  456. return http {
  457. authorizeExchange {
  458. authorize(anyExchange, permitAll)
  459. }
  460. httpBasic { }
  461. }
  462. }
  463. @Bean
  464. fun userDetailsService(): MapReactiveUserDetailsService {
  465. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  466. val rob = userBuilder.username("rob")
  467. .password("rob")
  468. .roles("USER")
  469. .build()
  470. val admin = userBuilder.username("admin")
  471. .password("admin")
  472. .roles("USER", "ADMIN")
  473. .build()
  474. return MapReactiveUserDetailsService(rob, admin)
  475. }
  476. }
  477. ----
  478. ======
  479. You can find a complete sample in {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method].