method-security.adoc 26 KB

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