method.adoc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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 GrantedAuthorityDefaults
  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. [[use-programmatic-authorization]]
  99. == Authorizing Methods Programmatically
  100. As you've already seen, there are several ways that you can specify non-trivial authorization rules using xref:servlet/authorization/method-security.adoc#authorization-expressions[Method Security SpEL expressions].
  101. There are a number of ways that you can instead allow your logic to be Java-based instead of SpEL-based.
  102. This gives use access the entire Java language for increased testability and flow control.
  103. === Using a Custom Bean in SpEL
  104. The first way to authorize a method programmatically is a two-step process.
  105. First, declare a bean that has a method that takes a `MethodSecurityExpressionOperations` instance like the following:
  106. [tabs]
  107. ======
  108. Java::
  109. +
  110. [source,java,role="primary"]
  111. ----
  112. @Component("authz")
  113. public class AuthorizationLogic {
  114. public decide(MethodSecurityExpressionOperations operations): Mono<Boolean> {
  115. // ... authorization logic
  116. }
  117. }
  118. ----
  119. Kotlin::
  120. +
  121. [source,kotlin,role="secondary"]
  122. ----
  123. @Component("authz")
  124. open class AuthorizationLogic {
  125. fun decide(val operations: MethodSecurityExpressionOperations): Mono<Boolean> {
  126. // ... authorization logic
  127. }
  128. }
  129. ----
  130. ======
  131. Then, reference that bean in your annotations in the following way:
  132. [tabs]
  133. ======
  134. Java::
  135. +
  136. [source,java,role="primary"]
  137. ----
  138. @Controller
  139. public class MyController {
  140. @PreAuthorize("@authz.decide(#root)")
  141. @GetMapping("/endpoint")
  142. public Mono<String> endpoint() {
  143. // ...
  144. }
  145. }
  146. ----
  147. Kotlin::
  148. +
  149. [source,kotlin,role="secondary"]
  150. ----
  151. @Controller
  152. open class MyController {
  153. @PreAuthorize("@authz.decide(#root)")
  154. @GetMapping("/endpoint")
  155. fun endpoint(): Mono<String> {
  156. // ...
  157. }
  158. }
  159. ----
  160. ======
  161. Spring Security will invoke the given method on that bean for each method invocation.
  162. What's nice about this is all your authorization logic is in a separate class that can be independently unit tested and verified for correctness.
  163. It also has access to the full Java language.
  164. [TIP]
  165. In addition to returning a `Mono<Boolean>`, you can also return `Mono.empty()` to indicate that the code abstains from making a decision.
  166. If you want to include more information about the nature of the decision, you can instead return a custom `AuthorizationDecision` like this:
  167. [tabs]
  168. ======
  169. Java::
  170. +
  171. [source,java,role="primary"]
  172. ----
  173. @Component("authz")
  174. public class AuthorizationLogic {
  175. public Mono<AuthorizationDecision> decide(MethodSecurityExpressionOperations operations) {
  176. // ... authorization logic
  177. return Mono.just(new MyAuthorizationDecision(false, details));
  178. }
  179. }
  180. ----
  181. Kotlin::
  182. +
  183. [source,kotlin,role="secondary"]
  184. ----
  185. @Component("authz")
  186. open class AuthorizationLogic {
  187. fun decide(val operations: MethodSecurityExpressionOperations): Mono<AuthorizationDecision> {
  188. // ... authorization logic
  189. return Mono.just(MyAuthorizationDecision(false, details))
  190. }
  191. }
  192. ----
  193. ======
  194. Or throw a custom `AuthorizationDeniedException` instance.
  195. Note, though, that returning an object is preferred as this doesn't incur the expense of generating a stacktrace.
  196. Then, you can access the custom details when you xref:servlet/authorization/method-security.adoc#fallback-values-authorization-denied[customize how the authorization result is handled].
  197. [[custom-authorization-managers]]
  198. === Using a Custom Authorization Manager
  199. The second way to authorize a method programmatically is to create a custom xref:servlet/authorization/architecture.adoc#_the_authorizationmanager[`AuthorizationManager`].
  200. First, declare an authorization manager instance, perhaps like this one:
  201. [tabs]
  202. ======
  203. Java::
  204. +
  205. [source,java,role="primary"]
  206. ----
  207. @Component
  208. public class MyPreAuthorizeAuthorizationManager implements ReactiveAuthorizationManager<MethodInvocation> {
  209. @Override
  210. public Mono<AuthorizationDecision> check(Supplier<Authentication> authentication, MethodInvocation invocation) {
  211. // ... authorization logic
  212. }
  213. }
  214. ----
  215. Kotlin::
  216. +
  217. [source,kotlin,role="secondary"]
  218. ----
  219. @Component
  220. class MyPreAuthorizeAuthorizationManager : ReactiveAuthorizationManager<MethodInvocation> {
  221. override fun check(authentication: Supplier<Authentication>, invocation: MethodInvocation): Mono<AuthorizationDecision> {
  222. // ... authorization logic
  223. }
  224. }
  225. ----
  226. ======
  227. Then, publish the method interceptor with a pointcut that corresponds to when you want that `ReactiveAuthorizationManager` to run.
  228. For example, you could replace how `@PreAuthorize` and `@PostAuthorize` work like so:
  229. .Only @PreAuthorize and @PostAuthorize Configuration
  230. [tabs]
  231. ======
  232. Java::
  233. +
  234. [source,java,role="primary"]
  235. ----
  236. @Configuration
  237. @EnableMethodSecurity(prePostEnabled = false)
  238. class MethodSecurityConfig {
  239. @Bean
  240. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  241. Advisor preAuthorize(MyPreAuthorizeAuthorizationManager manager) {
  242. return AuthorizationManagerBeforeReactiveMethodInterceptor.preAuthorize(manager);
  243. }
  244. @Bean
  245. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  246. Advisor postAuthorize(MyPostAuthorizeAuthorizationManager manager) {
  247. return AuthorizationManagerAfterReactiveMethodInterceptor.postAuthorize(manager);
  248. }
  249. }
  250. ----
  251. Kotlin::
  252. +
  253. [source,kotlin,role="secondary"]
  254. ----
  255. @Configuration
  256. @EnableMethodSecurity(prePostEnabled = false)
  257. class MethodSecurityConfig {
  258. @Bean
  259. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  260. fun preAuthorize(val manager: MyPreAuthorizeAuthorizationManager) : Advisor {
  261. return AuthorizationManagerBeforeReactiveMethodInterceptor.preAuthorize(manager)
  262. }
  263. @Bean
  264. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  265. fun postAuthorize(val manager: MyPostAuthorizeAuthorizationManager) : Advisor {
  266. return AuthorizationManagerAfterReactiveMethodInterceptor.postAuthorize(manager)
  267. }
  268. }
  269. ----
  270. ======
  271. [TIP]
  272. ====
  273. You can place your interceptor in between Spring Security method interceptors using the order constants specified in `AuthorizationInterceptorsOrder`.
  274. ====
  275. [[customizing-expression-handling]]
  276. === Customizing Expression Handling
  277. Or, third, you can customize how each SpEL expression is handled.
  278. To do that, you can expose a custom `MethodSecurityExpressionHandler`, like so:
  279. .Custom MethodSecurityExpressionHandler
  280. [tabs]
  281. ======
  282. Java::
  283. +
  284. [source,java,role="primary"]
  285. ----
  286. @Bean
  287. static MethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) {
  288. DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
  289. handler.setRoleHierarchy(roleHierarchy);
  290. return handler;
  291. }
  292. ----
  293. Kotlin::
  294. +
  295. [source,kotlin,role="secondary"]
  296. ----
  297. companion object {
  298. @Bean
  299. fun methodSecurityExpressionHandler(val roleHierarchy: RoleHierarchy) : MethodSecurityExpressionHandler {
  300. val handler = DefaultMethodSecurityExpressionHandler()
  301. handler.setRoleHierarchy(roleHierarchy)
  302. return handler
  303. }
  304. }
  305. ----
  306. Xml::
  307. +
  308. [source,xml,role="secondary"]
  309. ----
  310. <sec:method-security>
  311. <sec:expression-handler ref="myExpressionHandler"/>
  312. </sec:method-security>
  313. <bean id="myExpressionHandler"
  314. class="org.springframework.security.messaging.access.expression.DefaultMessageSecurityExpressionHandler">
  315. <property name="roleHierarchy" ref="roleHierarchy"/>
  316. </bean>
  317. ----
  318. ======
  319. [TIP]
  320. ====
  321. We expose `MethodSecurityExpressionHandler` using a `static` method to ensure that Spring publishes it before it initializes Spring Security's method security `@Configuration` classes
  322. ====
  323. You can also subclass xref:servlet/authorization/method-security.adoc#subclass-defaultmethodsecurityexpressionhandler[`DefaultMessageSecurityExpressionHandler`] to add your own custom authorization expressions beyond the defaults.
  324. [[jc-reactive-method-security-custom-authorization-manager]]
  325. === Custom Authorization Managers
  326. Method authorization is a combination of before- and after-method authorization.
  327. [NOTE]
  328. ====
  329. Before-method authorization is performed before the method is invoked.
  330. If that authorization denies access, the method is not invoked, and an `AccessDeniedException` is thrown.
  331. After-method authorization is performed after the method is invoked, but before the method returns to the caller.
  332. If that authorization denies access, the value is not returned, and an `AccessDeniedException` is thrown
  333. ====
  334. To recreate what adding `@EnableReactiveMethodSecurity(useAuthorizationManager=true)` does by default, you would publish the following configuration:
  335. .Full Pre-post Method Security Configuration
  336. [tabs]
  337. ======
  338. Java::
  339. +
  340. [source,java,role="primary"]
  341. ----
  342. @Configuration
  343. class MethodSecurityConfig {
  344. @Bean
  345. BeanDefinitionRegistryPostProcessor aopConfig() {
  346. return AopConfigUtils::registerAutoProxyCreatorIfNecessary;
  347. }
  348. @Bean
  349. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  350. PreFilterAuthorizationReactiveMethodInterceptor preFilterInterceptor() {
  351. return new PreFilterAuthorizationReactiveMethodInterceptor();
  352. }
  353. @Bean
  354. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  355. AuthorizationManagerBeforeReactiveMethodInterceptor preAuthorizeInterceptor() {
  356. return AuthorizationManagerBeforeReactiveMethodInterceptor.preAuthorize();
  357. }
  358. @Bean
  359. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  360. AuthorizationManagerAfterReactiveMethodInterceptor postAuthorizeInterceptor() {
  361. return AuthorizationManagerAfterReactiveMethodInterceptor.postAuthorize();
  362. }
  363. @Bean
  364. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  365. PostFilterAuthorizationReactiveMethodInterceptor postFilterInterceptor() {
  366. return new PostFilterAuthorizationReactiveMethodInterceptor();
  367. }
  368. }
  369. ----
  370. ======
  371. Notice that Spring Security's method security is built using Spring AOP.
  372. So, interceptors are invoked based on the order specified.
  373. This can be customized by calling `setOrder` on the interceptor instances like so:
  374. .Publish Custom Advisor
  375. [tabs]
  376. ======
  377. Java::
  378. +
  379. [source,java,role="primary"]
  380. ----
  381. @Bean
  382. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  383. Advisor postFilterAuthorizationMethodInterceptor() {
  384. PostFilterAuthorizationMethodInterceptor interceptor = new PostFilterAuthorizationReactiveMethodInterceptor();
  385. interceptor.setOrder(AuthorizationInterceptorOrders.POST_AUTHORIZE.getOrder() - 1);
  386. return interceptor;
  387. }
  388. ----
  389. ======
  390. You may want to only support `@PreAuthorize` in your application, in which case you can do the following:
  391. .Only @PreAuthorize Configuration
  392. [tabs]
  393. ======
  394. Java::
  395. +
  396. [source,java,role="primary"]
  397. ----
  398. @Configuration
  399. class MethodSecurityConfig {
  400. @Bean
  401. BeanDefinitionRegistryPostProcessor aopConfig() {
  402. return AopConfigUtils::registerAutoProxyCreatorIfNecessary;
  403. }
  404. @Bean
  405. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  406. Advisor preAuthorize() {
  407. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
  408. }
  409. }
  410. ----
  411. ======
  412. Or, you may have a custom before-method `ReactiveAuthorizationManager` that you want to add to the list.
  413. In this case, you will need to tell Spring Security both the `ReactiveAuthorizationManager` and to which methods and classes your authorization manager applies.
  414. Thus, you can configure Spring Security to invoke your `ReactiveAuthorizationManager` in between `@PreAuthorize` and `@PostAuthorize` like so:
  415. .Custom Before Advisor
  416. [tabs]
  417. ======
  418. Java::
  419. +
  420. [source,java,role="primary"]
  421. ----
  422. @EnableReactiveMethodSecurity(useAuthorizationManager=true)
  423. class MethodSecurityConfig {
  424. @Bean
  425. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  426. public Advisor customAuthorize() {
  427. JdkRegexpMethodPointcut pattern = new JdkRegexpMethodPointcut();
  428. pattern.setPattern("org.mycompany.myapp.service.*");
  429. ReactiveAuthorizationManager<MethodInvocation> rule = AuthorityAuthorizationManager.isAuthenticated();
  430. AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(pattern, rule);
  431. interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  432. return interceptor;
  433. }
  434. }
  435. ----
  436. ======
  437. [TIP]
  438. ====
  439. You can place your interceptor in between Spring Security method interceptors using the order constants specified in `AuthorizationInterceptorsOrder`.
  440. ====
  441. The same can be done for after-method authorization.
  442. After-method authorization is generally concerned with analysing the return value to verify access.
  443. For example, you might have a method that confirms that the account requested actually belongs to the logged-in user like so:
  444. .@PostAuthorize example
  445. [tabs]
  446. ======
  447. Java::
  448. +
  449. [source,java,role="primary"]
  450. ----
  451. public interface BankService {
  452. @PreAuthorize("hasRole('USER')")
  453. @PostAuthorize("returnObject.owner == authentication.name")
  454. Mono<Account> readAccount(Long id);
  455. }
  456. ----
  457. ======
  458. You can supply your own `AuthorizationMethodInterceptor` to customize how access to the return value is evaluated.
  459. For example, if you have your own custom annotation, you can configure it like so:
  460. .Custom After Advisor
  461. [tabs]
  462. ======
  463. Java::
  464. +
  465. [source,java,role="primary"]
  466. ----
  467. @EnableReactiveMethodSecurity(useAuthorizationManager=true)
  468. class MethodSecurityConfig {
  469. @Bean
  470. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  471. public Advisor customAuthorize(ReactiveAuthorizationManager<MethodInvocationResult> rules) {
  472. AnnotationMethodMatcher pattern = new AnnotationMethodMatcher(MySecurityAnnotation.class);
  473. AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(pattern, rules);
  474. interceptor.setOrder(AuthorizationInterceptorsOrder.POST_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  475. return interceptor;
  476. }
  477. }
  478. ----
  479. ======
  480. and it will be invoked after the `@PostAuthorize` interceptor.
  481. == EnableReactiveMethodSecurity
  482. [tabs]
  483. ======
  484. Java::
  485. +
  486. [source,java,role="primary"]
  487. ----
  488. Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
  489. Mono<String> messageByUsername = ReactiveSecurityContextHolder.getContext()
  490. .map(SecurityContext::getAuthentication)
  491. .map(Authentication::getName)
  492. .flatMap(this::findMessageByUsername)
  493. // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
  494. .contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
  495. StepVerifier.create(messageByUsername)
  496. .expectNext("Hi user")
  497. .verifyComplete();
  498. ----
  499. Kotlin::
  500. +
  501. [source,kotlin,role="secondary"]
  502. ----
  503. val authentication: Authentication = TestingAuthenticationToken("user", "password", "ROLE_USER")
  504. val messageByUsername: Mono<String> = ReactiveSecurityContextHolder.getContext()
  505. .map(SecurityContext::getAuthentication)
  506. .map(Authentication::getName)
  507. .flatMap(this::findMessageByUsername) // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
  508. .contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
  509. StepVerifier.create(messageByUsername)
  510. .expectNext("Hi user")
  511. .verifyComplete()
  512. ----
  513. ======
  514. Where `this::findMessageByUsername` is defined as:
  515. [tabs]
  516. ======
  517. Java::
  518. +
  519. [source,java,role="primary"]
  520. ----
  521. Mono<String> findMessageByUsername(String username) {
  522. return Mono.just("Hi " + username);
  523. }
  524. ----
  525. Kotlin::
  526. +
  527. [source,kotlin,role="secondary"]
  528. ----
  529. fun findMessageByUsername(username: String): Mono<String> {
  530. return Mono.just("Hi $username")
  531. }
  532. ----
  533. ======
  534. The following minimal method security configures method security in reactive applications:
  535. [tabs]
  536. ======
  537. Java::
  538. +
  539. [source,java,role="primary"]
  540. ----
  541. @Configuration
  542. @EnableReactiveMethodSecurity
  543. public class SecurityConfig {
  544. @Bean
  545. public MapReactiveUserDetailsService userDetailsService() {
  546. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  547. UserDetails rob = userBuilder.username("rob")
  548. .password("rob")
  549. .roles("USER")
  550. .build();
  551. UserDetails admin = userBuilder.username("admin")
  552. .password("admin")
  553. .roles("USER","ADMIN")
  554. .build();
  555. return new MapReactiveUserDetailsService(rob, admin);
  556. }
  557. }
  558. ----
  559. Kotlin::
  560. +
  561. [source,kotlin,role="secondary"]
  562. ----
  563. @Configuration
  564. @EnableReactiveMethodSecurity
  565. class SecurityConfig {
  566. @Bean
  567. fun userDetailsService(): MapReactiveUserDetailsService {
  568. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  569. val rob = userBuilder.username("rob")
  570. .password("rob")
  571. .roles("USER")
  572. .build()
  573. val admin = userBuilder.username("admin")
  574. .password("admin")
  575. .roles("USER", "ADMIN")
  576. .build()
  577. return MapReactiveUserDetailsService(rob, admin)
  578. }
  579. }
  580. ----
  581. ======
  582. Consider the following class:
  583. [tabs]
  584. ======
  585. Java::
  586. +
  587. [source,java,role="primary"]
  588. ----
  589. @Component
  590. public class HelloWorldMessageService {
  591. @PreAuthorize("hasRole('ADMIN')")
  592. public Mono<String> findMessage() {
  593. return Mono.just("Hello World!");
  594. }
  595. }
  596. ----
  597. Kotlin::
  598. +
  599. [source,kotlin,role="secondary"]
  600. ----
  601. @Component
  602. class HelloWorldMessageService {
  603. @PreAuthorize("hasRole('ADMIN')")
  604. fun findMessage(): Mono<String> {
  605. return Mono.just("Hello World!")
  606. }
  607. }
  608. ----
  609. ======
  610. Alternatively, the following class uses Kotlin coroutines:
  611. [tabs]
  612. ======
  613. Kotlin::
  614. +
  615. [source,kotlin,role="primary"]
  616. ----
  617. @Component
  618. class HelloWorldMessageService {
  619. @PreAuthorize("hasRole('ADMIN')")
  620. suspend fun findMessage(): String {
  621. delay(10)
  622. return "Hello World!"
  623. }
  624. }
  625. ----
  626. ======
  627. Combined with our configuration above, `@PreAuthorize("hasRole('ADMIN')")` ensures that `findByMessage` is invoked only by a user with the `ADMIN` role.
  628. Note that any of the expressions in standard method security work for `@EnableReactiveMethodSecurity`.
  629. However, at this time, we support only a return type of `Boolean` or `boolean` of the expression.
  630. This means that the expression must not block.
  631. 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:
  632. [tabs]
  633. ======
  634. Java::
  635. +
  636. [source,java,role="primary"]
  637. ----
  638. @Configuration
  639. @EnableWebFluxSecurity
  640. @EnableReactiveMethodSecurity
  641. public class SecurityConfig {
  642. @Bean
  643. SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
  644. return http
  645. // Demonstrate that method security works
  646. // Best practice to use both for defense in depth
  647. .authorizeExchange(exchanges -> exchanges
  648. .anyExchange().permitAll()
  649. )
  650. .httpBasic(withDefaults())
  651. .build();
  652. }
  653. @Bean
  654. MapReactiveUserDetailsService userDetailsService() {
  655. User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
  656. UserDetails rob = userBuilder.username("rob")
  657. .password("rob")
  658. .roles("USER")
  659. .build();
  660. UserDetails admin = userBuilder.username("admin")
  661. .password("admin")
  662. .roles("USER","ADMIN")
  663. .build();
  664. return new MapReactiveUserDetailsService(rob, admin);
  665. }
  666. }
  667. ----
  668. Kotlin::
  669. +
  670. [source,kotlin,role="secondary"]
  671. ----
  672. @Configuration
  673. @EnableWebFluxSecurity
  674. @EnableReactiveMethodSecurity
  675. class SecurityConfig {
  676. @Bean
  677. open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  678. return http {
  679. authorizeExchange {
  680. authorize(anyExchange, permitAll)
  681. }
  682. httpBasic { }
  683. }
  684. }
  685. @Bean
  686. fun userDetailsService(): MapReactiveUserDetailsService {
  687. val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
  688. val rob = userBuilder.username("rob")
  689. .password("rob")
  690. .roles("USER")
  691. .build()
  692. val admin = userBuilder.username("admin")
  693. .password("admin")
  694. .roles("USER", "ADMIN")
  695. .build()
  696. return MapReactiveUserDetailsService(rob, admin)
  697. }
  698. }
  699. ----
  700. ======
  701. You can find a complete sample in {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method].