method.adoc 16 KB

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