method-security.adoc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. [[jc-method]]
  2. = Method Security
  3. From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods.
  4. It provides support for JSR-250 annotation security as well as the framework's original `@Secured` annotation.
  5. From 3.0 you can also make use of new xref:servlet/authorization/expression-based.adoc#el-access[expression-based annotations].
  6. You can apply security to a single bean, using the `intercept-methods` element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts.
  7. [[jc-enable-method-security]]
  8. == EnableMethodSecurity
  9. In Spring Security 5.6, we can enable annotation-based security using the `@EnableMethodSecurity` annotation on any `@Configuration` instance.
  10. This improves upon `@EnableGlobalMethodSecurity` in a number of ways. `@EnableMethodSecurity`:
  11. 1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters.
  12. This simplifies reuse and customization.
  13. 2. Favors direct bean-based configuration, instead of requiring extending `GlobalMethodSecurityConfiguration` to customize beans
  14. 3. Is built using native Spring AOP, removing abstractions and allowing you to use Spring AOP building blocks to customize
  15. 4. Checks for conflicting annotations to ensure an unambiguous security configuration
  16. 5. Complies with JSR-250
  17. 6. Enables `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` by default
  18. [NOTE]
  19. ====
  20. For earlier versions, please read about similar support with <<jc-enable-global-method-security, @EnableGlobalMethodSecurity>>.
  21. ====
  22. For example, the following would enable Spring Security's `@PreAuthorize` annotation:
  23. .Method Security Configuration
  24. [tabs]
  25. ======
  26. Java::
  27. +
  28. [source,java,role="primary"]
  29. ----
  30. @EnableMethodSecurity
  31. public class MethodSecurityConfig {
  32. // ...
  33. }
  34. ----
  35. Kotlin::
  36. +
  37. [source,kotlin,role="secondary"]
  38. ----
  39. @EnableMethodSecurity
  40. class MethodSecurityConfig {
  41. // ...
  42. }
  43. ----
  44. Xml::
  45. +
  46. [source,xml,role="secondary"]
  47. ----
  48. <sec:method-security/>
  49. ----
  50. ======
  51. Adding an annotation to a method (on a class or interface) would then limit the access to that method accordingly.
  52. Spring Security's native annotation support defines a set of attributes for the method.
  53. These will be passed to the `DefaultAuthorizationMethodInterceptorChain` for it to make the actual decision:
  54. .Method Security Annotation Usage
  55. [tabs]
  56. ======
  57. Java::
  58. +
  59. [source,java,role="primary"]
  60. ----
  61. public interface BankService {
  62. @PreAuthorize("hasRole('USER')")
  63. Account readAccount(Long id);
  64. @PreAuthorize("hasRole('USER')")
  65. List<Account> findAccounts();
  66. @PreAuthorize("hasRole('TELLER')")
  67. Account post(Account account, Double amount);
  68. }
  69. ----
  70. Kotlin::
  71. +
  72. [source,kotlin,role="secondary"]
  73. ----
  74. interface BankService {
  75. @PreAuthorize("hasRole('USER')")
  76. fun readAccount(id : Long) : Account
  77. @PreAuthorize("hasRole('USER')")
  78. fun findAccounts() : List<Account>
  79. @PreAuthorize("hasRole('TELLER')")
  80. fun post(account : Account, amount : Double) : Account
  81. }
  82. ----
  83. ======
  84. You can enable support for Spring Security's `@Secured` annotation using:
  85. .@Secured Configuration
  86. [tabs]
  87. ======
  88. Java::
  89. +
  90. [source,java,role="primary"]
  91. ----
  92. @EnableMethodSecurity(securedEnabled = true)
  93. public class MethodSecurityConfig {
  94. // ...
  95. }
  96. ----
  97. Kotlin::
  98. +
  99. [source,kotlin,role="secondary"]
  100. ----
  101. @EnableMethodSecurity(securedEnabled = true)
  102. class MethodSecurityConfig {
  103. // ...
  104. }
  105. ----
  106. Xml::
  107. +
  108. [source,xml,role="secondary"]
  109. ----
  110. <sec:method-security secured-enabled="true"/>
  111. ----
  112. ======
  113. or JSR-250 using:
  114. .JSR-250 Configuration
  115. [tabs]
  116. ======
  117. Java::
  118. +
  119. [source,java,role="primary"]
  120. ----
  121. @EnableMethodSecurity(jsr250Enabled = true)
  122. public class MethodSecurityConfig {
  123. // ...
  124. }
  125. ----
  126. Kotlin::
  127. +
  128. [source,kotlin,role="secondary"]
  129. ----
  130. @EnableMethodSecurity(jsr250Enabled = true)
  131. class MethodSecurityConfig {
  132. // ...
  133. }
  134. ----
  135. Xml::
  136. +
  137. [source,xml,role="secondary"]
  138. ----
  139. <sec:method-security jsr250-enabled="true"/>
  140. ----
  141. ======
  142. === Customizing Authorization
  143. Spring Security's `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` ship with rich expression-based support.
  144. [[jc-method-security-custom-expression-handler]]
  145. If you need to customize the way that expressions are handled, you can expose a custom `MethodSecurityExpressionHandler`, like so:
  146. .Custom MethodSecurityExpressionHandler
  147. [tabs]
  148. ======
  149. Java::
  150. +
  151. [source,java,role="primary"]
  152. ----
  153. @Bean
  154. static MethodSecurityExpressionHandler methodSecurityExpressionHandler() {
  155. DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
  156. handler.setTrustResolver(myCustomTrustResolver);
  157. return handler;
  158. }
  159. ----
  160. Kotlin::
  161. +
  162. [source,kotlin,role="secondary"]
  163. ----
  164. companion object {
  165. @Bean
  166. fun methodSecurityExpressionHandler() : MethodSecurityExpressionHandler {
  167. val handler = DefaultMethodSecurityExpressionHandler();
  168. handler.setTrustResolver(myCustomTrustResolver);
  169. return handler;
  170. }
  171. }
  172. ----
  173. Xml::
  174. +
  175. [source,xml,role="secondary"]
  176. ----
  177. <sec:method-security>
  178. <sec:expression-handler ref="myExpressionHandler"/>
  179. </sec:method-security>
  180. <bean id="myExpressionHandler"
  181. class="org.springframework.security.messaging.access.expression.DefaultMessageSecurityExpressionHandler">
  182. <property name="trustResolver" ref="myCustomTrustResolver"/>
  183. </bean>
  184. ----
  185. ======
  186. [TIP]
  187. ====
  188. We expose `MethodSecurityExpressionHandler` using a `static` method to ensure that Spring publishes it before it initializes Spring Security's method security `@Configuration` classes
  189. ====
  190. Also, for role-based authorization, Spring Security adds a default `ROLE_` prefix, which is uses when evaluating expressions like `hasRole`.
  191. [[jc-method-security-custom-granted-authority-defaults]]
  192. You can configure the authorization rules to use a different prefix by exposing a `GrantedAuthorityDefaults` bean, like so:
  193. .Custom MethodSecurityExpressionHandler
  194. [tabs]
  195. ======
  196. Java::
  197. +
  198. [source,java,role="primary"]
  199. ----
  200. @Bean
  201. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  202. static GrantedAuthorityDefaults grantedAuthorityDefaults() {
  203. return new GrantedAuthorityDefaults("MYPREFIX_");
  204. }
  205. ----
  206. Kotlin::
  207. +
  208. [source,kotlin,role="secondary"]
  209. ----
  210. companion object {
  211. @Bean
  212. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  213. fun grantedAuthorityDefaults() : GrantedAuthorityDefaults {
  214. return GrantedAuthorityDefaults("MYPREFIX_");
  215. }
  216. }
  217. ----
  218. Xml::
  219. +
  220. [source,xml,role="secondary"]
  221. ----
  222. <sec:method-security/>
  223. <bean id="grantedAuthorityDefaults" class="org.springframework.security.config.core.GrantedAuthorityDefaults">
  224. <constructor-arg value="MYPREFIX_"/>
  225. </bean>
  226. ----
  227. ======
  228. [TIP]
  229. ====
  230. We expose `GrantedAuthorityDefaults` using a `static` method to ensure that Spring publishes it before it initializes Spring Security's method security `@Configuration` classes.
  231. 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]).
  232. ====
  233. [[jc-method-security-custom-authorization-manager]]
  234. === Custom Authorization Managers
  235. Method authorization is a combination of before- and after-method authorization.
  236. [NOTE]
  237. ====
  238. Before-method authorization is performed before the method is invoked.
  239. If that authorization denies access, the method is not invoked, and an `AccessDeniedException` is thrown.
  240. After-method authorization is performed after the method is invoked, but before the method returns to the caller.
  241. If that authorization denies access, the value is not returned, and an `AccessDeniedException` is thrown
  242. ====
  243. To recreate what adding `@EnableMethodSecurity` does by default, you would publish the following configuration:
  244. .Full Pre-post Method Security Configuration
  245. [tabs]
  246. ======
  247. Java::
  248. +
  249. [source,java,role="primary"]
  250. ----
  251. @EnableMethodSecurity(prePostEnabled = false)
  252. class MethodSecurityConfig {
  253. @Bean
  254. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  255. Advisor preFilterAuthorizationMethodInterceptor() {
  256. return new PreFilterAuthorizationMethodInterceptor();
  257. }
  258. @Bean
  259. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  260. Advisor preAuthorizeAuthorizationMethodInterceptor() {
  261. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
  262. }
  263. @Bean
  264. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  265. Advisor postAuthorizeAuthorizationMethodInterceptor() {
  266. return AuthorizationManagerAfterMethodInterceptor.postAuthorize();
  267. }
  268. @Bean
  269. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  270. Advisor postFilterAuthorizationMethodInterceptor() {
  271. return new PostFilterAuthorizationMethodInterceptor();
  272. }
  273. }
  274. ----
  275. Kotlin::
  276. +
  277. [source,kotlin,role="secondary"]
  278. ----
  279. @EnableMethodSecurity(prePostEnabled = false)
  280. class MethodSecurityConfig {
  281. @Bean
  282. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  283. fun preFilterAuthorizationMethodInterceptor() : Advisor {
  284. return PreFilterAuthorizationMethodInterceptor();
  285. }
  286. @Bean
  287. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  288. fun preAuthorizeAuthorizationMethodInterceptor() : Advisor {
  289. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
  290. }
  291. @Bean
  292. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  293. fun postAuthorizeAuthorizationMethodInterceptor() : Advisor {
  294. return AuthorizationManagerAfterMethodInterceptor.postAuthorize();
  295. }
  296. @Bean
  297. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  298. fun postFilterAuthorizationMethodInterceptor() : Advisor {
  299. return PostFilterAuthorizationMethodInterceptor();
  300. }
  301. }
  302. ----
  303. Xml::
  304. +
  305. [source,xml,role="secondary"]
  306. ----
  307. <sec:method-security pre-post-enabled="false"/>
  308. <aop:config/>
  309. <bean id="preFilterAuthorizationMethodInterceptor"
  310. class="org.springframework.security.authorization.method.PreFilterAuthorizationMethodInterceptor"/>
  311. <bean id="preAuthorizeAuthorizationMethodInterceptor"
  312. class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor"
  313. factory-method="preAuthorize"/>
  314. <bean id="postAuthorizeAuthorizationMethodInterceptor"
  315. class="org.springframework.security.authorization.method.AuthorizationManagerAfterMethodInterceptor"
  316. factory-method="postAuthorize"/>
  317. <bean id="postFilterAuthorizationMethodInterceptor"
  318. class="org.springframework.security.authorization.method.PostFilterAuthorizationMethodInterceptor"/>
  319. ----
  320. ======
  321. Notice that Spring Security's method security is built using Spring AOP.
  322. So, interceptors are invoked based on the order specified.
  323. This can be customized by calling `setOrder` on the interceptor instances like so:
  324. .Publish Custom Advisor
  325. [tabs]
  326. ======
  327. Java::
  328. +
  329. [source,java,role="primary"]
  330. ----
  331. @Bean
  332. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  333. Advisor postFilterAuthorizationMethodInterceptor() {
  334. PostFilterAuthorizationMethodInterceptor interceptor = new PostFilterAuthorizationMethodInterceptor();
  335. interceptor.setOrder(AuthorizationInterceptorOrders.POST_AUTHORIZE.getOrder() - 1);
  336. return interceptor;
  337. }
  338. ----
  339. Kotlin::
  340. +
  341. [source,kotlin,role="secondary"]
  342. ----
  343. @Bean
  344. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  345. fun postFilterAuthorizationMethodInterceptor() : Advisor {
  346. val interceptor = PostFilterAuthorizationMethodInterceptor();
  347. interceptor.setOrder(AuthorizationInterceptorOrders.POST_AUTHORIZE.getOrder() - 1);
  348. return interceptor;
  349. }
  350. ----
  351. Xml::
  352. +
  353. [source,xml,role="secondary"]
  354. ----
  355. <bean id="postFilterAuthorizationMethodInterceptor"
  356. class="org.springframework.security.authorization.method.PostFilterAuthorizationMethodInterceptor">
  357. <property name="order"
  358. value="#{T(org.springframework.security.authorization.method.AuthorizationInterceptorsOrder).POST_AUTHORIZE.getOrder() -1}"/>
  359. </bean>
  360. ----
  361. ======
  362. You may want to only support `@PreAuthorize` in your application, in which case you can do the following:
  363. .Only @PreAuthorize Configuration
  364. [tabs]
  365. ======
  366. Java::
  367. +
  368. [source,java,role="primary"]
  369. ----
  370. @EnableMethodSecurity(prePostEnabled = false)
  371. class MethodSecurityConfig {
  372. @Bean
  373. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  374. Advisor preAuthorize() {
  375. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
  376. }
  377. }
  378. ----
  379. Kotlin::
  380. +
  381. [source,kotlin,role="secondary"]
  382. ----
  383. @EnableMethodSecurity(prePostEnabled = false)
  384. class MethodSecurityConfig {
  385. @Bean
  386. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  387. fun preAuthorize() : Advisor {
  388. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize()
  389. }
  390. }
  391. ----
  392. Xml::
  393. +
  394. [source,xml,role="secondary"]
  395. ----
  396. <sec:method-security pre-post-enabled="false"/>
  397. <aop:config/>
  398. <bean id="preAuthorizeAuthorizationMethodInterceptor"
  399. class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor"
  400. factory-method="preAuthorize"/>
  401. ----
  402. ======
  403. Or, you may have a custom before-method `AuthorizationManager` that you want to add to the list.
  404. In this case, you will need to tell Spring Security both the `AuthorizationManager` and to which methods and classes your authorization manager applies.
  405. Thus, you can configure Spring Security to invoke your `AuthorizationManager` in between `@PreAuthorize` and `@PostAuthorize` like so:
  406. .Custom Before Advisor
  407. [tabs]
  408. ======
  409. Java::
  410. +
  411. [source,java,role="primary"]
  412. ----
  413. @EnableMethodSecurity
  414. class MethodSecurityConfig {
  415. @Bean
  416. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  417. public Advisor customAuthorize() {
  418. JdkRegexpMethodPointcut pattern = new JdkRegexpMethodPointcut();
  419. pattern.setPattern("org.mycompany.myapp.service.*");
  420. AuthorizationManager<MethodInvocation> rule = AuthorityAuthorizationManager.isAuthenticated();
  421. AuthorizationManagerBeforeMethodInterceptor interceptor = new AuthorizationManagerBeforeMethodInterceptor(pattern, rule);
  422. interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  423. return interceptor;
  424. }
  425. }
  426. ----
  427. Kotlin::
  428. +
  429. [source,kotlin,role="secondary"]
  430. ----
  431. @EnableMethodSecurity
  432. class MethodSecurityConfig {
  433. @Bean
  434. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  435. fun customAuthorize() : Advisor {
  436. val pattern = JdkRegexpMethodPointcut();
  437. pattern.setPattern("org.mycompany.myapp.service.*");
  438. val rule = AuthorityAuthorizationManager.isAuthenticated();
  439. val interceptor = AuthorizationManagerBeforeMethodInterceptor(pattern, rule);
  440. interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  441. return interceptor;
  442. }
  443. }
  444. ----
  445. Xml::
  446. +
  447. [source,xml,role="secondary"]
  448. ----
  449. <sec:method-security/>
  450. <aop:config/>
  451. <bean id="customAuthorize"
  452. class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor">
  453. <constructor-arg>
  454. <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut">
  455. <property name="pattern" value="org.mycompany.myapp.service.*"/>
  456. </bean>
  457. </constructor-arg>
  458. <constructor-arg>
  459. <bean class="org.springframework.security.authorization.AuthorityAuthorizationManager"
  460. factory-method="isAuthenticated"/>
  461. </constructor-arg>
  462. <property name="order"
  463. value="#{T(org.springframework.security.authorization.method.AuthorizationInterceptorsOrder).PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1}"/>
  464. </bean>
  465. ----
  466. ======
  467. [TIP]
  468. ====
  469. You can place your interceptor in between Spring Security method interceptors using the order constants specified in `AuthorizationInterceptorsOrder`.
  470. ====
  471. The same can be done for after-method authorization.
  472. After-method authorization is generally concerned with analysing the return value to verify access.
  473. For example, you might have a method that confirms that the account requested actually belongs to the logged-in user like so:
  474. .@PostAuthorize example
  475. [tabs]
  476. ======
  477. Java::
  478. +
  479. [source,java,role="primary"]
  480. ----
  481. public interface BankService {
  482. @PreAuthorize("hasRole('USER')")
  483. @PostAuthorize("returnObject.owner == authentication.name")
  484. Account readAccount(Long id);
  485. }
  486. ----
  487. Kotlin::
  488. +
  489. [source,kotlin,role="secondary"]
  490. ----
  491. interface BankService {
  492. @PreAuthorize("hasRole('USER')")
  493. @PostAuthorize("returnObject.owner == authentication.name")
  494. fun readAccount(id : Long) : Account
  495. }
  496. ----
  497. ======
  498. You can supply your own `AuthorizationMethodInterceptor` to customize how access to the return value is evaluated.
  499. For example, if you have your own custom annotation, you can configure it like so:
  500. .Custom After Advisor
  501. [tabs]
  502. ======
  503. Java::
  504. +
  505. [source,java,role="primary"]
  506. ----
  507. @EnableMethodSecurity
  508. class MethodSecurityConfig {
  509. @Bean
  510. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  511. public Advisor customAuthorize(AuthorizationManager<MethodInvocationResult> rules) {
  512. AnnotationMatchingPointcut pattern = new AnnotationMatchingPointcut(MySecurityAnnotation.class);
  513. AuthorizationManagerAfterMethodInterceptor interceptor = new AuthorizationManagerAfterMethodInterceptor(pattern, rules);
  514. interceptor.setOrder(AuthorizationInterceptorsOrder.POST_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  515. return interceptor;
  516. }
  517. }
  518. ----
  519. Kotlin::
  520. +
  521. [source,kotlin,role="secondary"]
  522. ----
  523. @EnableMethodSecurity
  524. class MethodSecurityConfig {
  525. @Bean
  526. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  527. fun customAuthorize(rules : AuthorizationManager<MethodInvocationResult>) : Advisor {
  528. val pattern = AnnotationMatchingPointcut(MySecurityAnnotation::class.java);
  529. val interceptor = AuthorizationManagerAfterMethodInterceptor(pattern, rules);
  530. interceptor.setOrder(AuthorizationInterceptorsOrder.POST_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  531. return interceptor;
  532. }
  533. }
  534. ----
  535. Xml::
  536. +
  537. [source,xml,role="secondary"]
  538. ----
  539. <sec:method-security/>
  540. <aop:config/>
  541. <bean id="customAuthorize"
  542. class="org.springframework.security.authorization.method.AuthorizationManagerAfterMethodInterceptor">
  543. <constructor-arg>
  544. <bean class="org.springframework.aop.support.annotation.AnnotationMethodMatcher">
  545. <constructor-arg value="#{T(org.mycompany.MySecurityAnnotation)}"/>
  546. </bean>
  547. </constructor-arg>
  548. <constructor-arg>
  549. <bean class="org.springframework.security.authorization.AuthorityAuthorizationManager"
  550. factory-method="isAuthenticated"/>
  551. </constructor-arg>
  552. <property name="order"
  553. value="#{T(org.springframework.security.authorization.method.AuthorizationInterceptorsOrder).PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1}"/>
  554. </bean>
  555. ----
  556. ======
  557. and it will be invoked after the `@PostAuthorize` interceptor.
  558. [[jc-enable-global-method-security]]
  559. == EnableGlobalMethodSecurity
  560. We can enable annotation-based security using the `@EnableGlobalMethodSecurity` annotation on any `@Configuration` instance.
  561. For example, the following would enable Spring Security's `@Secured` annotation.
  562. [tabs]
  563. ======
  564. Java::
  565. +
  566. [source,java,role="primary"]
  567. ----
  568. @EnableGlobalMethodSecurity(securedEnabled = true)
  569. public class MethodSecurityConfig {
  570. // ...
  571. }
  572. ----
  573. Kotlin::
  574. +
  575. [source,kotlin,role="secondary"]
  576. ----
  577. @EnableGlobalMethodSecurity(securedEnabled = true)
  578. open class MethodSecurityConfig {
  579. // ...
  580. }
  581. ----
  582. ======
  583. Adding an annotation to a method (on a class or interface) would then limit the access to that method accordingly.
  584. Spring Security's native annotation support defines a set of attributes for the method.
  585. These will be passed to the AccessDecisionManager for it to make the actual decision:
  586. [tabs]
  587. ======
  588. Java::
  589. +
  590. [source,java,role="primary"]
  591. ----
  592. public interface BankService {
  593. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  594. public Account readAccount(Long id);
  595. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  596. public Account[] findAccounts();
  597. @Secured("ROLE_TELLER")
  598. public Account post(Account account, double amount);
  599. }
  600. ----
  601. Kotlin::
  602. +
  603. [source,kotlin,role="secondary"]
  604. ----
  605. interface BankService {
  606. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  607. fun readAccount(id: Long): Account
  608. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  609. fun findAccounts(): Array<Account>
  610. @Secured("ROLE_TELLER")
  611. fun post(account: Account, amount: Double): Account
  612. }
  613. ----
  614. ======
  615. Support for JSR-250 annotations can be enabled using
  616. [tabs]
  617. ======
  618. Java::
  619. +
  620. [source,java,role="primary"]
  621. ----
  622. @EnableGlobalMethodSecurity(jsr250Enabled = true)
  623. public class MethodSecurityConfig {
  624. // ...
  625. }
  626. ----
  627. Kotlin::
  628. +
  629. [source,kotlin,role="secondary"]
  630. ----
  631. @EnableGlobalMethodSecurity(jsr250Enabled = true)
  632. open class MethodSecurityConfig {
  633. // ...
  634. }
  635. ----
  636. ======
  637. These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security's native annotations.
  638. To use the new expression-based syntax, you would use
  639. [tabs]
  640. ======
  641. Java::
  642. +
  643. [source,java,role="primary"]
  644. ----
  645. @EnableGlobalMethodSecurity(prePostEnabled = true)
  646. public class MethodSecurityConfig {
  647. // ...
  648. }
  649. ----
  650. Kotlin::
  651. +
  652. [source,kotlin,role="secondary"]
  653. ----
  654. @EnableGlobalMethodSecurity(prePostEnabled = true)
  655. open class MethodSecurityConfig {
  656. // ...
  657. }
  658. ----
  659. ======
  660. and the equivalent Java code would be
  661. [tabs]
  662. ======
  663. Java::
  664. +
  665. [source,java,role="primary"]
  666. ----
  667. public interface BankService {
  668. @PreAuthorize("isAnonymous()")
  669. public Account readAccount(Long id);
  670. @PreAuthorize("isAnonymous()")
  671. public Account[] findAccounts();
  672. @PreAuthorize("hasAuthority('ROLE_TELLER')")
  673. public Account post(Account account, double amount);
  674. }
  675. ----
  676. Kotlin::
  677. +
  678. [source,kotlin,role="secondary"]
  679. ----
  680. interface BankService {
  681. @PreAuthorize("isAnonymous()")
  682. fun readAccount(id: Long): Account
  683. @PreAuthorize("isAnonymous()")
  684. fun findAccounts(): Array<Account>
  685. @PreAuthorize("hasAuthority('ROLE_TELLER')")
  686. fun post(account: Account, amount: Double): Account
  687. }
  688. ----
  689. ======
  690. == GlobalMethodSecurityConfiguration
  691. Sometimes you may need to perform operations that are more complicated than are possible with the `@EnableGlobalMethodSecurity` annotation allow.
  692. For these instances, you can extend the `GlobalMethodSecurityConfiguration` ensuring that the `@EnableGlobalMethodSecurity` annotation is present on your subclass.
  693. For example, if you wanted to provide a custom `MethodSecurityExpressionHandler`, you could use the following configuration:
  694. [tabs]
  695. ======
  696. Java::
  697. +
  698. [source,java,role="primary"]
  699. ----
  700. @EnableGlobalMethodSecurity(prePostEnabled = true)
  701. public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
  702. @Override
  703. protected MethodSecurityExpressionHandler createExpressionHandler() {
  704. // ... create and return custom MethodSecurityExpressionHandler ...
  705. return expressionHandler;
  706. }
  707. }
  708. ----
  709. Kotlin::
  710. +
  711. [source,kotlin,role="secondary"]
  712. ----
  713. @EnableGlobalMethodSecurity(prePostEnabled = true)
  714. open class MethodSecurityConfig : GlobalMethodSecurityConfiguration() {
  715. override fun createExpressionHandler(): MethodSecurityExpressionHandler {
  716. // ... create and return custom MethodSecurityExpressionHandler ...
  717. return expressionHandler
  718. }
  719. }
  720. ----
  721. ======
  722. For additional information about methods that can be overridden, refer to the `GlobalMethodSecurityConfiguration` Javadoc.
  723. [[ns-global-method]]
  724. == The <global-method-security> Element
  725. This element is used to enable annotation-based security in your application (by setting the appropriate attributes on the element), and also to group together security pointcut declarations which will be applied across your entire application context.
  726. You should only declare one `<global-method-security>` element.
  727. The following declaration would enable support for Spring Security's `@Secured`:
  728. [source,xml]
  729. ----
  730. <global-method-security secured-annotations="enabled" />
  731. ----
  732. Adding an annotation to a method (on an class or interface) would then limit the access to that method accordingly.
  733. Spring Security's native annotation support defines a set of attributes for the method.
  734. These will be passed to the `AccessDecisionManager` for it to make the actual decision:
  735. [tabs]
  736. ======
  737. Java::
  738. +
  739. [source,java,role="primary"]
  740. ----
  741. public interface BankService {
  742. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  743. public Account readAccount(Long id);
  744. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  745. public Account[] findAccounts();
  746. @Secured("ROLE_TELLER")
  747. public Account post(Account account, double amount);
  748. }
  749. ----
  750. Kotlin::
  751. +
  752. [source,kotlin,role="secondary"]
  753. ----
  754. interface BankService {
  755. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  756. fun readAccount(id: Long): Account
  757. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  758. fun findAccounts(): Array<Account>
  759. @Secured("ROLE_TELLER")
  760. fun post(account: Account, amount: Double): Account
  761. }
  762. ----
  763. ======
  764. Support for JSR-250 annotations can be enabled using
  765. [source,xml]
  766. ----
  767. <global-method-security jsr250-annotations="enabled" />
  768. ----
  769. These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security's native annotations.
  770. To use the new expression-based syntax, you would use
  771. [source,xml]
  772. ----
  773. <global-method-security pre-post-annotations="enabled" />
  774. ----
  775. and the equivalent Java code would be
  776. [tabs]
  777. ======
  778. Java::
  779. +
  780. [source,java,role="primary"]
  781. ----
  782. public interface BankService {
  783. @PreAuthorize("isAnonymous()")
  784. public Account readAccount(Long id);
  785. @PreAuthorize("isAnonymous()")
  786. public Account[] findAccounts();
  787. @PreAuthorize("hasAuthority('ROLE_TELLER')")
  788. public Account post(Account account, double amount);
  789. }
  790. ----
  791. Kotlin::
  792. +
  793. [source,kotlin,role="secondary"]
  794. ----
  795. interface BankService {
  796. @PreAuthorize("isAnonymous()")
  797. fun readAccount(id: Long): Account
  798. @PreAuthorize("isAnonymous()")
  799. fun findAccounts(): Array<Account>
  800. @PreAuthorize("hasAuthority('ROLE_TELLER')")
  801. fun post(account: Account, amount: Double): Account
  802. }
  803. ----
  804. ======
  805. Expression-based annotations are a good choice if you need to define simple rules that go beyond checking the role names against the user's list of authorities.
  806. [NOTE]
  807. ====
  808. The annotated methods will only be secured for instances which are defined as Spring beans (in the same application context in which method-security is enabled).
  809. If you want to secure instances which are not created by Spring (using the `new` operator, for example) then you need to use AspectJ.
  810. ====
  811. [NOTE]
  812. ====
  813. You can enable more than one type of annotation in the same application, but only one type should be used for any interface or class as the behaviour will not be well-defined otherwise.
  814. If two annotations are found which apply to a particular method, then only one of them will be applied.
  815. ====
  816. [[ns-protect-pointcut]]
  817. == Adding Security Pointcuts using protect-pointcut
  818. The use of `protect-pointcut` is particularly powerful, as it allows you to apply security to many beans with only a simple declaration.
  819. Consider the following example:
  820. [source,xml]
  821. ----
  822. <global-method-security>
  823. <protect-pointcut expression="execution(* com.mycompany.*Service.*(..))"
  824. access="ROLE_USER"/>
  825. </global-method-security>
  826. ----
  827. This will protect all methods on beans declared in the application context whose classes are in the `com.mycompany` package and whose class names end in "Service".
  828. Only users with the `ROLE_USER` role will be able to invoke these methods.
  829. As with URL matching, the most specific matches must come first in the list of pointcuts, as the first matching expression will be used.
  830. Security annotations take precedence over pointcuts.