method-security.adoc 26 KB

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