method-security.adoc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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. static GrantedAuthorityDefaults grantedAuthorityDefaults() {
  202. return new GrantedAuthorityDefaults("MYPREFIX_");
  203. }
  204. ----
  205. Kotlin::
  206. +
  207. [source,kotlin,role="secondary"]
  208. ----
  209. companion object {
  210. @Bean
  211. fun grantedAuthorityDefaults() : GrantedAuthorityDefaults {
  212. return GrantedAuthorityDefaults("MYPREFIX_");
  213. }
  214. }
  215. ----
  216. Xml::
  217. +
  218. [source,xml,role="secondary"]
  219. ----
  220. <sec:method-security/>
  221. <bean id="grantedAuthorityDefaults" class="org.springframework.security.config.core.GrantedAuthorityDefaults">
  222. <constructor-arg value="MYPREFIX_"/>
  223. </bean>
  224. ----
  225. ======
  226. [TIP]
  227. ====
  228. We expose `GrantedAuthorityDefaults` using a `static` method to ensure that Spring publishes it before it initializes Spring Security's method security `@Configuration` classes
  229. ====
  230. [[jc-method-security-custom-authorization-manager]]
  231. === Custom Authorization Managers
  232. Method authorization is a combination of before- and after-method authorization.
  233. [NOTE]
  234. ====
  235. Before-method authorization is performed before the method is invoked.
  236. If that authorization denies access, the method is not invoked, and an `AccessDeniedException` is thrown.
  237. After-method authorization is performed after the method is invoked, but before the method returns to the caller.
  238. If that authorization denies access, the value is not returned, and an `AccessDeniedException` is thrown
  239. ====
  240. To recreate what adding `@EnableMethodSecurity` does by default, you would publish the following configuration:
  241. .Full Pre-post Method Security Configuration
  242. [tabs]
  243. ======
  244. Java::
  245. +
  246. [source,java,role="primary"]
  247. ----
  248. @EnableMethodSecurity(prePostEnabled = false)
  249. class MethodSecurityConfig {
  250. @Bean
  251. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  252. Advisor preFilterAuthorizationMethodInterceptor() {
  253. return new PreFilterAuthorizationMethodInterceptor();
  254. }
  255. @Bean
  256. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  257. Advisor preAuthorizeAuthorizationMethodInterceptor() {
  258. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
  259. }
  260. @Bean
  261. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  262. Advisor postAuthorizeAuthorizationMethodInterceptor() {
  263. return AuthorizationManagerAfterMethodInterceptor.postAuthorize();
  264. }
  265. @Bean
  266. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  267. Advisor postFilterAuthorizationMethodInterceptor() {
  268. return new PostFilterAuthorizationMethodInterceptor();
  269. }
  270. }
  271. ----
  272. Kotlin::
  273. +
  274. [source,kotlin,role="secondary"]
  275. ----
  276. @EnableMethodSecurity(prePostEnabled = false)
  277. class MethodSecurityConfig {
  278. @Bean
  279. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  280. fun preFilterAuthorizationMethodInterceptor() : Advisor {
  281. return PreFilterAuthorizationMethodInterceptor();
  282. }
  283. @Bean
  284. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  285. fun preAuthorizeAuthorizationMethodInterceptor() : Advisor {
  286. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
  287. }
  288. @Bean
  289. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  290. fun postAuthorizeAuthorizationMethodInterceptor() : Advisor {
  291. return AuthorizationManagerAfterMethodInterceptor.postAuthorize();
  292. }
  293. @Bean
  294. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  295. fun postFilterAuthorizationMethodInterceptor() : Advisor {
  296. return PostFilterAuthorizationMethodInterceptor();
  297. }
  298. }
  299. ----
  300. Xml::
  301. +
  302. [source,xml,role="secondary"]
  303. ----
  304. <sec:method-security pre-post-enabled="false"/>
  305. <aop:config/>
  306. <bean id="preFilterAuthorizationMethodInterceptor"
  307. class="org.springframework.security.authorization.method.PreFilterAuthorizationMethodInterceptor"/>
  308. <bean id="preAuthorizeAuthorizationMethodInterceptor"
  309. class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor"
  310. factory-method="preAuthorize"/>
  311. <bean id="postAuthorizeAuthorizationMethodInterceptor"
  312. class="org.springframework.security.authorization.method.AuthorizationManagerAfterMethodInterceptor"
  313. factory-method="postAuthorize"/>
  314. <bean id="postFilterAuthorizationMethodInterceptor"
  315. class="org.springframework.security.authorization.method.PostFilterAuthorizationMethodInterceptor"/>
  316. ----
  317. ======
  318. Notice that Spring Security's method security is built using Spring AOP.
  319. So, interceptors are invoked based on the order specified.
  320. This can be customized by calling `setOrder` on the interceptor instances like so:
  321. .Publish Custom Advisor
  322. [tabs]
  323. ======
  324. Java::
  325. +
  326. [source,java,role="primary"]
  327. ----
  328. @Bean
  329. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  330. Advisor postFilterAuthorizationMethodInterceptor() {
  331. PostFilterAuthorizationMethodInterceptor interceptor = new PostFilterAuthorizationMethodInterceptor();
  332. interceptor.setOrder(AuthorizationInterceptorOrders.POST_AUTHORIZE.getOrder() - 1);
  333. return interceptor;
  334. }
  335. ----
  336. Kotlin::
  337. +
  338. [source,kotlin,role="secondary"]
  339. ----
  340. @Bean
  341. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  342. fun postFilterAuthorizationMethodInterceptor() : Advisor {
  343. val interceptor = PostFilterAuthorizationMethodInterceptor();
  344. interceptor.setOrder(AuthorizationInterceptorOrders.POST_AUTHORIZE.getOrder() - 1);
  345. return interceptor;
  346. }
  347. ----
  348. Xml::
  349. +
  350. [source,xml,role="secondary"]
  351. ----
  352. <bean id="postFilterAuthorizationMethodInterceptor"
  353. class="org.springframework.security.authorization.method.PostFilterAuthorizationMethodInterceptor">
  354. <property name="order"
  355. value="#{T(org.springframework.security.authorization.method.AuthorizationInterceptorsOrder).POST_AUTHORIZE.getOrder() -1}"/>
  356. </bean>
  357. ----
  358. ======
  359. You may want to only support `@PreAuthorize` in your application, in which case you can do the following:
  360. .Only @PreAuthorize Configuration
  361. [tabs]
  362. ======
  363. Java::
  364. +
  365. [source,java,role="primary"]
  366. ----
  367. @EnableMethodSecurity(prePostEnabled = false)
  368. class MethodSecurityConfig {
  369. @Bean
  370. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  371. Advisor preAuthorize() {
  372. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
  373. }
  374. }
  375. ----
  376. Kotlin::
  377. +
  378. [source,kotlin,role="secondary"]
  379. ----
  380. @EnableMethodSecurity(prePostEnabled = false)
  381. class MethodSecurityConfig {
  382. @Bean
  383. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  384. fun preAuthorize() : Advisor {
  385. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize()
  386. }
  387. }
  388. ----
  389. Xml::
  390. +
  391. [source,xml,role="secondary"]
  392. ----
  393. <sec:method-security pre-post-enabled="false"/>
  394. <aop:config/>
  395. <bean id="preAuthorizeAuthorizationMethodInterceptor"
  396. class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor"
  397. factory-method="preAuthorize"/>
  398. ----
  399. ======
  400. Or, you may have a custom before-method `AuthorizationManager` that you want to add to the list.
  401. In this case, you will need to tell Spring Security both the `AuthorizationManager` and to which methods and classes your authorization manager applies.
  402. Thus, you can configure Spring Security to invoke your `AuthorizationManager` in between `@PreAuthorize` and `@PostAuthorize` like so:
  403. .Custom Before Advisor
  404. [tabs]
  405. ======
  406. Java::
  407. +
  408. [source,java,role="primary"]
  409. ----
  410. @EnableMethodSecurity
  411. class MethodSecurityConfig {
  412. @Bean
  413. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  414. public Advisor customAuthorize() {
  415. JdkRegexpMethodPointcut pattern = new JdkRegexpMethodPointcut();
  416. pattern.setPattern("org.mycompany.myapp.service.*");
  417. AuthorizationManager<MethodInvocation> rule = AuthorityAuthorizationManager.isAuthenticated();
  418. AuthorizationManagerBeforeMethodInterceptor interceptor = new AuthorizationManagerBeforeMethodInterceptor(pattern, rule);
  419. interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  420. return interceptor;
  421. }
  422. }
  423. ----
  424. Kotlin::
  425. +
  426. [source,kotlin,role="secondary"]
  427. ----
  428. @EnableMethodSecurity
  429. class MethodSecurityConfig {
  430. @Bean
  431. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  432. fun customAuthorize() : Advisor {
  433. val pattern = JdkRegexpMethodPointcut();
  434. pattern.setPattern("org.mycompany.myapp.service.*");
  435. val rule = AuthorityAuthorizationManager.isAuthenticated();
  436. val interceptor = AuthorizationManagerBeforeMethodInterceptor(pattern, rule);
  437. interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  438. return interceptor;
  439. }
  440. }
  441. ----
  442. Xml::
  443. +
  444. [source,xml,role="secondary"]
  445. ----
  446. <sec:method-security/>
  447. <aop:config/>
  448. <bean id="customAuthorize"
  449. class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor">
  450. <constructor-arg>
  451. <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut">
  452. <property name="pattern" value="org.mycompany.myapp.service.*"/>
  453. </bean>
  454. </constructor-arg>
  455. <constructor-arg>
  456. <bean class="org.springframework.security.authorization.AuthorityAuthorizationManager"
  457. factory-method="isAuthenticated"/>
  458. </constructor-arg>
  459. <property name="order"
  460. value="#{T(org.springframework.security.authorization.method.AuthorizationInterceptorsOrder).PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1}"/>
  461. </bean>
  462. ----
  463. ======
  464. [TIP]
  465. ====
  466. You can place your interceptor in between Spring Security method interceptors using the order constants specified in `AuthorizationInterceptorsOrder`.
  467. ====
  468. The same can be done for after-method authorization.
  469. After-method authorization is generally concerned with analysing the return value to verify access.
  470. For example, you might have a method that confirms that the account requested actually belongs to the logged-in user like so:
  471. .@PostAuthorize example
  472. [tabs]
  473. ======
  474. Java::
  475. +
  476. [source,java,role="primary"]
  477. ----
  478. public interface BankService {
  479. @PreAuthorize("hasRole('USER')")
  480. @PostAuthorize("returnObject.owner == authentication.name")
  481. Account readAccount(Long id);
  482. }
  483. ----
  484. Kotlin::
  485. +
  486. [source,kotlin,role="secondary"]
  487. ----
  488. interface BankService {
  489. @PreAuthorize("hasRole('USER')")
  490. @PostAuthorize("returnObject.owner == authentication.name")
  491. fun readAccount(id : Long) : Account
  492. }
  493. ----
  494. ======
  495. You can supply your own `AuthorizationMethodInterceptor` to customize how access to the return value is evaluated.
  496. For example, if you have your own custom annotation, you can configure it like so:
  497. .Custom After Advisor
  498. [tabs]
  499. ======
  500. Java::
  501. +
  502. [source,java,role="primary"]
  503. ----
  504. @EnableMethodSecurity
  505. class MethodSecurityConfig {
  506. @Bean
  507. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  508. public Advisor customAuthorize(AuthorizationManager<MethodInvocationResult> rules) {
  509. AnnotationMatchingPointcut pattern = new AnnotationMatchingPointcut(MySecurityAnnotation.class);
  510. AuthorizationManagerAfterMethodInterceptor interceptor = new AuthorizationManagerAfterMethodInterceptor(pattern, rules);
  511. interceptor.setOrder(AuthorizationInterceptorsOrder.POST_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  512. return interceptor;
  513. }
  514. }
  515. ----
  516. Kotlin::
  517. +
  518. [source,kotlin,role="secondary"]
  519. ----
  520. @EnableMethodSecurity
  521. class MethodSecurityConfig {
  522. @Bean
  523. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  524. fun customAuthorize(rules : AuthorizationManager<MethodInvocationResult>) : Advisor {
  525. val pattern = AnnotationMatchingPointcut(MySecurityAnnotation::class.java);
  526. val interceptor = AuthorizationManagerAfterMethodInterceptor(pattern, rules);
  527. interceptor.setOrder(AuthorizationInterceptorsOrder.POST_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1);
  528. return interceptor;
  529. }
  530. }
  531. ----
  532. Xml::
  533. +
  534. [source,xml,role="secondary"]
  535. ----
  536. <sec:method-security/>
  537. <aop:config/>
  538. <bean id="customAuthorize"
  539. class="org.springframework.security.authorization.method.AuthorizationManagerAfterMethodInterceptor">
  540. <constructor-arg>
  541. <bean class="org.springframework.aop.support.annotation.AnnotationMethodMatcher">
  542. <constructor-arg value="#{T(org.mycompany.MySecurityAnnotation)}"/>
  543. </bean>
  544. </constructor-arg>
  545. <constructor-arg>
  546. <bean class="org.springframework.security.authorization.AuthorityAuthorizationManager"
  547. factory-method="isAuthenticated"/>
  548. </constructor-arg>
  549. <property name="order"
  550. value="#{T(org.springframework.security.authorization.method.AuthorizationInterceptorsOrder).PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1}"/>
  551. </bean>
  552. ----
  553. ======
  554. and it will be invoked after the `@PostAuthorize` interceptor.
  555. [[jc-enable-global-method-security]]
  556. == EnableGlobalMethodSecurity
  557. We can enable annotation-based security using the `@EnableGlobalMethodSecurity` annotation on any `@Configuration` instance.
  558. For example, the following would enable Spring Security's `@Secured` annotation.
  559. [tabs]
  560. ======
  561. Java::
  562. +
  563. [source,java,role="primary"]
  564. ----
  565. @EnableGlobalMethodSecurity(securedEnabled = true)
  566. public class MethodSecurityConfig {
  567. // ...
  568. }
  569. ----
  570. Kotlin::
  571. +
  572. [source,kotlin,role="secondary"]
  573. ----
  574. @EnableGlobalMethodSecurity(securedEnabled = true)
  575. open class MethodSecurityConfig {
  576. // ...
  577. }
  578. ----
  579. ======
  580. Adding an annotation to a method (on a class or interface) would then limit the access to that method accordingly.
  581. Spring Security's native annotation support defines a set of attributes for the method.
  582. These will be passed to the AccessDecisionManager for it to make the actual decision:
  583. [tabs]
  584. ======
  585. Java::
  586. +
  587. [source,java,role="primary"]
  588. ----
  589. public interface BankService {
  590. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  591. public Account readAccount(Long id);
  592. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  593. public Account[] findAccounts();
  594. @Secured("ROLE_TELLER")
  595. public Account post(Account account, double amount);
  596. }
  597. ----
  598. Kotlin::
  599. +
  600. [source,kotlin,role="secondary"]
  601. ----
  602. interface BankService {
  603. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  604. fun readAccount(id: Long): Account
  605. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  606. fun findAccounts(): Array<Account>
  607. @Secured("ROLE_TELLER")
  608. fun post(account: Account, amount: Double): Account
  609. }
  610. ----
  611. ======
  612. Support for JSR-250 annotations can be enabled using
  613. [tabs]
  614. ======
  615. Java::
  616. +
  617. [source,java,role="primary"]
  618. ----
  619. @EnableGlobalMethodSecurity(jsr250Enabled = true)
  620. public class MethodSecurityConfig {
  621. // ...
  622. }
  623. ----
  624. Kotlin::
  625. +
  626. [source,kotlin,role="secondary"]
  627. ----
  628. @EnableGlobalMethodSecurity(jsr250Enabled = true)
  629. open class MethodSecurityConfig {
  630. // ...
  631. }
  632. ----
  633. ======
  634. These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security's native annotations.
  635. To use the new expression-based syntax, you would use
  636. [tabs]
  637. ======
  638. Java::
  639. +
  640. [source,java,role="primary"]
  641. ----
  642. @EnableGlobalMethodSecurity(prePostEnabled = true)
  643. public class MethodSecurityConfig {
  644. // ...
  645. }
  646. ----
  647. Kotlin::
  648. +
  649. [source,kotlin,role="secondary"]
  650. ----
  651. @EnableGlobalMethodSecurity(prePostEnabled = true)
  652. open class MethodSecurityConfig {
  653. // ...
  654. }
  655. ----
  656. ======
  657. and the equivalent Java code would be
  658. [tabs]
  659. ======
  660. Java::
  661. +
  662. [source,java,role="primary"]
  663. ----
  664. public interface BankService {
  665. @PreAuthorize("isAnonymous()")
  666. public Account readAccount(Long id);
  667. @PreAuthorize("isAnonymous()")
  668. public Account[] findAccounts();
  669. @PreAuthorize("hasAuthority('ROLE_TELLER')")
  670. public Account post(Account account, double amount);
  671. }
  672. ----
  673. Kotlin::
  674. +
  675. [source,kotlin,role="secondary"]
  676. ----
  677. interface BankService {
  678. @PreAuthorize("isAnonymous()")
  679. fun readAccount(id: Long): Account
  680. @PreAuthorize("isAnonymous()")
  681. fun findAccounts(): Array<Account>
  682. @PreAuthorize("hasAuthority('ROLE_TELLER')")
  683. fun post(account: Account, amount: Double): Account
  684. }
  685. ----
  686. ======
  687. == GlobalMethodSecurityConfiguration
  688. Sometimes you may need to perform operations that are more complicated than are possible with the `@EnableGlobalMethodSecurity` annotation allow.
  689. For these instances, you can extend the `GlobalMethodSecurityConfiguration` ensuring that the `@EnableGlobalMethodSecurity` annotation is present on your subclass.
  690. For example, if you wanted to provide a custom `MethodSecurityExpressionHandler`, you could use the following configuration:
  691. [tabs]
  692. ======
  693. Java::
  694. +
  695. [source,java,role="primary"]
  696. ----
  697. @EnableGlobalMethodSecurity(prePostEnabled = true)
  698. public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
  699. @Override
  700. protected MethodSecurityExpressionHandler createExpressionHandler() {
  701. // ... create and return custom MethodSecurityExpressionHandler ...
  702. return expressionHandler;
  703. }
  704. }
  705. ----
  706. Kotlin::
  707. +
  708. [source,kotlin,role="secondary"]
  709. ----
  710. @EnableGlobalMethodSecurity(prePostEnabled = true)
  711. open class MethodSecurityConfig : GlobalMethodSecurityConfiguration() {
  712. override fun createExpressionHandler(): MethodSecurityExpressionHandler {
  713. // ... create and return custom MethodSecurityExpressionHandler ...
  714. return expressionHandler
  715. }
  716. }
  717. ----
  718. ======
  719. For additional information about methods that can be overridden, refer to the `GlobalMethodSecurityConfiguration` Javadoc.
  720. [[ns-global-method]]
  721. == The <global-method-security> Element
  722. 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.
  723. You should only declare one `<global-method-security>` element.
  724. The following declaration would enable support for Spring Security's `@Secured`:
  725. [source,xml]
  726. ----
  727. <global-method-security secured-annotations="enabled" />
  728. ----
  729. Adding an annotation to a method (on an class or interface) would then limit the access to that method accordingly.
  730. Spring Security's native annotation support defines a set of attributes for the method.
  731. These will be passed to the `AccessDecisionManager` for it to make the actual decision:
  732. [tabs]
  733. ======
  734. Java::
  735. +
  736. [source,java,role="primary"]
  737. ----
  738. public interface BankService {
  739. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  740. public Account readAccount(Long id);
  741. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  742. public Account[] findAccounts();
  743. @Secured("ROLE_TELLER")
  744. public Account post(Account account, double amount);
  745. }
  746. ----
  747. Kotlin::
  748. +
  749. [source,kotlin,role="secondary"]
  750. ----
  751. interface BankService {
  752. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  753. fun readAccount(id: Long): Account
  754. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
  755. fun findAccounts(): Array<Account>
  756. @Secured("ROLE_TELLER")
  757. fun post(account: Account, amount: Double): Account
  758. }
  759. ----
  760. ======
  761. Support for JSR-250 annotations can be enabled using
  762. [source,xml]
  763. ----
  764. <global-method-security jsr250-annotations="enabled" />
  765. ----
  766. These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security's native annotations.
  767. To use the new expression-based syntax, you would use
  768. [source,xml]
  769. ----
  770. <global-method-security pre-post-annotations="enabled" />
  771. ----
  772. and the equivalent Java code would be
  773. [tabs]
  774. ======
  775. Java::
  776. +
  777. [source,java,role="primary"]
  778. ----
  779. public interface BankService {
  780. @PreAuthorize("isAnonymous()")
  781. public Account readAccount(Long id);
  782. @PreAuthorize("isAnonymous()")
  783. public Account[] findAccounts();
  784. @PreAuthorize("hasAuthority('ROLE_TELLER')")
  785. public Account post(Account account, double amount);
  786. }
  787. ----
  788. Kotlin::
  789. +
  790. [source,kotlin,role="secondary"]
  791. ----
  792. interface BankService {
  793. @PreAuthorize("isAnonymous()")
  794. fun readAccount(id: Long): Account
  795. @PreAuthorize("isAnonymous()")
  796. fun findAccounts(): Array<Account>
  797. @PreAuthorize("hasAuthority('ROLE_TELLER')")
  798. fun post(account: Account, amount: Double): Account
  799. }
  800. ----
  801. ======
  802. 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.
  803. [NOTE]
  804. ====
  805. 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).
  806. If you want to secure instances which are not created by Spring (using the `new` operator, for example) then you need to use AspectJ.
  807. ====
  808. [NOTE]
  809. ====
  810. 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.
  811. If two annotations are found which apply to a particular method, then only one of them will be applied.
  812. ====
  813. [[ns-protect-pointcut]]
  814. == Adding Security Pointcuts using protect-pointcut
  815. The use of `protect-pointcut` is particularly powerful, as it allows you to apply security to many beans with only a simple declaration.
  816. Consider the following example:
  817. [source,xml]
  818. ----
  819. <global-method-security>
  820. <protect-pointcut expression="execution(* com.mycompany.*Service.*(..))"
  821. access="ROLE_USER"/>
  822. </global-method-security>
  823. ----
  824. 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".
  825. Only users with the `ROLE_USER` role will be able to invoke these methods.
  826. As with URL matching, the most specific matches must come first in the list of pointcuts, as the first matching expression will be used.
  827. Security annotations take precedence over pointcuts.