method.adoc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. ====
  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. .contextWrite(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. .contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
  264. StepVerifier.create(messageByUsername)
  265. .expectNext("Hi user")
  266. .verifyComplete()
  267. ----
  268. ====
  269. Where `this::findMessageByUsername` is 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. The following minimal method security configures method security in reactive applications:
  287. ====
  288. .Java
  289. [source,java,role="primary"]
  290. ----
  291. @Configuration
  292. @EnableReactiveMethodSecurity
  293. public class SecurityConfig {
  294. @Bean
  295. public MapReactiveUserDetailsService userDetailsService() {
  296. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  297. UserDetails rob = userBuilder.username("rob")
  298. .password("rob")
  299. .roles("USER")
  300. .build();
  301. UserDetails admin = userBuilder.username("admin")
  302. .password("admin")
  303. .roles("USER","ADMIN")
  304. .build();
  305. return new MapReactiveUserDetailsService(rob, admin);
  306. }
  307. }
  308. ----
  309. .Kotlin
  310. [source,kotlin,role="secondary"]
  311. ----
  312. @Configuration
  313. @EnableReactiveMethodSecurity
  314. class SecurityConfig {
  315. @Bean
  316. fun userDetailsService(): MapReactiveUserDetailsService {
  317. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  318. val rob = userBuilder.username("rob")
  319. .password("rob")
  320. .roles("USER")
  321. .build()
  322. val admin = userBuilder.username("admin")
  323. .password("admin")
  324. .roles("USER", "ADMIN")
  325. .build()
  326. return MapReactiveUserDetailsService(rob, admin)
  327. }
  328. }
  329. ----
  330. ====
  331. Consider the following class:
  332. ====
  333. .Java
  334. [source,java,role="primary"]
  335. ----
  336. @Component
  337. public class HelloWorldMessageService {
  338. @PreAuthorize("hasRole('ADMIN')")
  339. public Mono<String> findMessage() {
  340. return Mono.just("Hello World!");
  341. }
  342. }
  343. ----
  344. .Kotlin
  345. [source,kotlin,role="secondary"]
  346. ----
  347. @Component
  348. class HelloWorldMessageService {
  349. @PreAuthorize("hasRole('ADMIN')")
  350. fun findMessage(): Mono<String> {
  351. return Mono.just("Hello World!")
  352. }
  353. }
  354. ----
  355. ====
  356. Alternatively, the following class uses Kotlin coroutines:
  357. ====
  358. .Kotlin
  359. [source,kotlin,role="primary"]
  360. ----
  361. @Component
  362. class HelloWorldMessageService {
  363. @PreAuthorize("hasRole('ADMIN')")
  364. suspend fun findMessage(): String {
  365. delay(10)
  366. return "Hello World!"
  367. }
  368. }
  369. ----
  370. ====
  371. Combined with our configuration above, `@PreAuthorize("hasRole('ADMIN')")` ensures that `findByMessage` is invoked only by a user with the `ADMIN` role.
  372. Note that any of the expressions in standard method security work for `@EnableReactiveMethodSecurity`.
  373. However, at this time, we support only a return type of `Boolean` or `boolean` of the expression.
  374. This means that the expression must not block.
  375. 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:
  376. ====
  377. .Java
  378. [source,java,role="primary"]
  379. ----
  380. @Configuration
  381. @EnableWebFluxSecurity
  382. @EnableReactiveMethodSecurity
  383. public class SecurityConfig {
  384. @Bean
  385. SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
  386. return http
  387. // Demonstrate that method security works
  388. // Best practice to use both for defense in depth
  389. .authorizeExchange(exchanges -> exchanges
  390. .anyExchange().permitAll()
  391. )
  392. .httpBasic(withDefaults())
  393. .build();
  394. }
  395. @Bean
  396. MapReactiveUserDetailsService userDetailsService() {
  397. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  398. UserDetails rob = userBuilder.username("rob")
  399. .password("rob")
  400. .roles("USER")
  401. .build();
  402. UserDetails admin = userBuilder.username("admin")
  403. .password("admin")
  404. .roles("USER","ADMIN")
  405. .build();
  406. return new MapReactiveUserDetailsService(rob, admin);
  407. }
  408. }
  409. ----
  410. .Kotlin
  411. [source,kotlin,role="secondary"]
  412. ----
  413. @Configuration
  414. @EnableWebFluxSecurity
  415. @EnableReactiveMethodSecurity
  416. class SecurityConfig {
  417. @Bean
  418. open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  419. return http {
  420. authorizeExchange {
  421. authorize(anyExchange, permitAll)
  422. }
  423. httpBasic { }
  424. }
  425. }
  426. @Bean
  427. fun userDetailsService(): MapReactiveUserDetailsService {
  428. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  429. val rob = userBuilder.username("rob")
  430. .password("rob")
  431. .roles("USER")
  432. .build()
  433. val admin = userBuilder.username("admin")
  434. .password("admin")
  435. .roles("USER", "ADMIN")
  436. .build()
  437. return MapReactiveUserDetailsService(rob, admin)
  438. }
  439. }
  440. ----
  441. ====
  442. You can find a complete sample in {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method].