method-security.adoc 26 KB

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