method-security.adoc 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782
  1. [[jc-method]]
  2. = Method Security
  3. :figures: servlet/authorization
  4. In addition to xref:servlet/authorization/authorize-http-requests.adoc[modeling authorization at the request level], Spring Security also supports modeling at the method level.
  5. [[activate-method-security]]
  6. You can activate it in your application by annotating any `@Configuration` class with `@EnableMethodSecurity` or adding `<method-security>` to any XML configuration file, like so:
  7. [tabs]
  8. ======
  9. Java::
  10. +
  11. [source,java,role="primary"]
  12. ----
  13. @EnableMethodSecurity
  14. ----
  15. Kotlin::
  16. +
  17. [source,kotlin,role="secondary"]
  18. ----
  19. @EnableMethodSecurity
  20. ----
  21. Xml::
  22. +
  23. [source,xml,role="secondary"]
  24. ----
  25. <sec:method-security/>
  26. ----
  27. ======
  28. Then, you are immediately able to annotate any Spring-managed class or method with <<use-preauthorize, `@PreAuthorize`>>, <<use-postauthorize,`@PostAuthorize`>>, <<use-prefilter,`@PreFilter`>>, and <<use-postfilter,`@PostFilter`>> to authorize method invocations, including the input parameters and return values.
  29. [NOTE]
  30. {spring-boot-reference-url}using.html#using.build-systems.starters[Spring Boot Starter Security] does not activate method-level authorization by default.
  31. Method Security supports many other use cases as well including <<use-aspectj, AspectJ support>>, <<use-programmatic-authorization,custom annotations>>, and several configuration points.
  32. Consider learning about the following use cases:
  33. * <<migration-enableglobalmethodsecurity, Migrating from `@EnableGlobalMethodSecurity`>>
  34. * Understanding <<method-security-architecture,how method security works>> and reasons to use it
  35. * Comparing <<request-vs-method,request-level and method-level authorization>>
  36. * Authorizing methods with <<use-preauthorize,`@PreAuthorize`>> and <<use-postauthorize,`@PostAuthorize`>>
  37. * Filtering methods with <<use-prefilter,`@PreFilter`>> and <<use-postfilter,`@PostFilter`>>
  38. * Authorizing methods with <<use-jsr250,JSR-250 annotations>>
  39. * Authorizing methods with <<use-aspectj,AspectJ expressions>>
  40. * Integrating with <<weave-aspectj,AspectJ byte-code weaving>>
  41. * Coordinating with <<changing-the-order,@Transactional and other AOP-based annotations>>
  42. * Customizing <<customizing-expression-handling,SpEL expression handling>>
  43. * Integrating with <<custom-authorization-managers,custom authorization systems>>
  44. [[method-security-architecture]]
  45. == How Method Security Works
  46. Spring Security's method authorization support is handy for:
  47. * Extracting fine-grained authorization logic; for example, when the method parameters and return values contribute to the authorization decision.
  48. * Enforcing security at the service layer
  49. * Stylistically favoring annotation-based over `HttpSecurity`-based configuration
  50. And since Method Security is built using {spring-framework-reference-url}core.html#aop-api[Spring AOP], you have access to all its expressive power to override Spring Security's defaults as needed.
  51. As already mentioned, you begin by adding `@EnableMethodSecurity` to a `@Configuration` class or `<sec:method-security/>` in a Spring XML configuration file.
  52. [[use-method-security]]
  53. [NOTE]
  54. ====
  55. This annotation and XML element supercede `@EnableGlobalMethodSecurity` and `<sec:global-method-security/>`, respectively.
  56. They offer the following improvements:
  57. 1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters.
  58. This simplifies reuse and customization.
  59. 2. Favors direct bean-based configuration, instead of requiring extending `GlobalMethodSecurityConfiguration` to customize beans
  60. 3. Is built using native Spring AOP, removing abstractions and allowing you to use Spring AOP building blocks to customize
  61. 4. Checks for conflicting annotations to ensure an unambiguous security configuration
  62. 5. Complies with JSR-250
  63. 6. Enables `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` by default
  64. If you are using `@EnableGlobalMethodSecurity` or `<global-method-security/>`, these are now deprecated, and you are encouraged to migrate.
  65. ====
  66. Method authorization is a combination of before- and after-method authorization.
  67. Consider a service bean that is annotated in the following way:
  68. [tabs]
  69. ======
  70. Java::
  71. +
  72. [source,java,role="primary"]
  73. ----
  74. @Service
  75. public class MyCustomerService {
  76. @PreAuthorize("hasAuthority('permission:read')")
  77. @PostAuthorize("returnObject.owner == authentication.name")
  78. public Customer readCustomer(String id) { ... }
  79. }
  80. ----
  81. Kotlin::
  82. +
  83. [source,kotlin,role="secondary"]
  84. ----
  85. @Service
  86. open class MyCustomerService {
  87. @PreAuthorize("hasAuthority('permission:read')")
  88. @PostAuthorize("returnObject.owner == authentication.name")
  89. fun readCustomer(val id: String): Customer { ... }
  90. }
  91. ----
  92. ======
  93. A given invocation to `MyCustomerService#readCustomer` may look something like this when Method Security <<activate-method-security,is activated>>:
  94. image::{figures}/methodsecurity.png[]
  95. 1. Spring AOP invokes its proxy method for `readCustomer`. Among the proxy's other advisors, it invokes an {security-api-url}org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptor/html[`AuthorizationManagerBeforeMethodInterceptor`] that matches <<annotation-method-pointcuts,the `@PreAuthorize` pointcut>>
  96. 2. The interceptor invokes {security-api-url}org/springframework/security/authorization/method/PreAuthorizeAuthorizationManager.html[`PreAuthorizeAuthorizationManager#check`]
  97. 3. The authorization manager uses a `MethodSecurityExpressionHandler` to parse the annotation's <<authorization-expressions,SpEL expression>> and constructs a corresponding `EvaluationContext` from a `MethodSecurityExpressionRoot` containing xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[a `Supplier<Authentication>`] and `MethodInvocation`.
  98. 4. The interceptor uses this context to evaluate the expression; specifically, it reads xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[the `Authentication`] from the `Supplier` and checks whether it has `permission:read` in its collection of xref:servlet/authorization/architecture.adoc#authz-authorities[authorities]
  99. 5. If the evaluation passes, then Spring AOP proceeds to invoke the method.
  100. 6. If not, the interceptor publishes an `AuthorizationDeniedEvent` and throws an {security-api-url}org/springframework/security/access/AccessDeniedException.html[`AccessDeniedException`] which xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[the `ExceptionTranslationFilter`] catches and returns a 403 status code to the response
  101. 7. After the method returns, Spring AOP invokes an {security-api-url}org/springframework/security/authorization/method/AuthorizationManagerAfterMethodInterceptor.html[`AuthorizationManagerAfterMethodInterceptor`] that matches <<annotation-method-pointcuts,the `@PostAuthorize` pointcut>>, operating the same as above, but with {security-api-url}org/springframework/security/authorization/method/PostAuthorizeAuthorizationManager.html[`PostAuthorizeAuthorizationManager`]
  102. 8. If the evaluation passes (in this case, the return value belongs to the logged-in user), processing continues normally
  103. 9. If not, the interceptor publishes an `AuthorizationDeniedEvent` and throws an {security-api-url}org/springframework/security/access/AccessDeniedException.html[`AccessDeniedException`], which xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[the `ExceptionTranslationFilter`] catches and returns a 403 status code to the response
  104. [NOTE]
  105. If the method is not being called in the context of an HTTP request, you will likely need to handle the `AccessDeniedException` yourself
  106. [[unanimous-based-authorization-decisions]]
  107. === Multiple Annotations Are Computed In Series
  108. As demonstrated above, if a method invocation involves multiple <<authorizing-with-annotations,Method Security annotations>>, each of those is processed one at a time.
  109. This means that they can collectively be thought of as being "anded" together.
  110. In other words, for an invocation to be authorized, all annotation inspections need to pass authorization.
  111. [[repeated-annotations]]
  112. === Repeated Annotations Are Not Supported
  113. That said, it is not supported to repeat the same annotation on the same method.
  114. For example, you cannot place `@PreAuthorize` twice on the same method.
  115. Instead, use SpEL's boolean support or its support for delegating to a separate bean.
  116. [[annotation-method-pointcuts]]
  117. === Each Annotation Has Its Own Pointcut
  118. Each annotation has its own pointcut instance that looks for that annotation or its <<meta-annotations,meta-annotation>> counterparts across the entire object hierarchy, starting at <<class-or-interface-annotations,the method and its enclosing class>>.
  119. You can see the specifics of this in {security-api-url}org/springframework/security/authorization/method/AuthorizationMethodPointcuts.html[`AuthorizationMethodPointcuts`].
  120. [[annotation-method-interceptors]]
  121. === Each Annotation Has Its Own Method Interceptor
  122. Each annotation has its own dedicated method interceptor.
  123. The reason for this is to make things more composable.
  124. For example, if needed, you can disable the Spring Security defaults and <<_enabling_certain_annotations,publish only the `@PostAuthorize` method interceptor>>.
  125. The method interceptors are as follows:
  126. * For <<use-preauthorize,`@PreAuthorize`>>, Spring Security uses {security-api-url}org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptor.html[`AuthenticationManagerBeforeMethodInterceptor#preAuthorize`], which in turn uses {security-api-url}org/springframework/security/authorization/method/PreAuthorizeAuthorizationManager.html[`PreAuthorizeAuthorizationManager`]
  127. * For <<use-postauthorize,`@PostAuthorize`>>, Spring Security uses {security-api-url}org/springframework/security/authorization/method/AuthorizationManagerAfterMethodInterceptor.html[`AuthenticationManagerAfterMethodInterceptor#postAuthorize`], which in turn uses {security-api-url}org/springframework/security/authorization/method/PostAuthorizeAuthorizationManager.html[`PostAuthorizeAuthorizationManager`]
  128. * For <<use-prefilter,`@PreFilter`>>, Spring Security uses {security-api-url}org/springframework/security/authorization/method/PreFilterAuthorizationMethodInterceptor.html[`PreFilterAuthorizationMethodInterceptor`]
  129. * For <<use-postfilter,`@PostFilter`>>, Spring Security uses {security-api-url}org/springframework/security/authorization/method/PostFilterAuthorizationMethodInterceptor.html[`PostFilterAuthorizationMethodInterceptor`]
  130. * For <<use-secured,`@Secured`>>, Spring Security uses {security-api-url}org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptor.html[`AuthenticationManagerBeforeMethodInterceptor#secured`], which in turn uses {security-api-url}org/springframework/security/authorization/method/SecuredAuthorizationManager.html[`SecuredAuthorizationManager`]
  131. * For JSR-250 annotations, Spring Security uses {security-api-url}org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptor.html[`AuthenticationManagerBeforeMethodInterceptor#jsr250`], which in turn uses {security-api-url}org/springframework/security/authorization/method/Jsr250AuthorizationManager.html[`Jsr250AuthorizationManager`]
  132. Generally speaking, you can consider the following listing as representative of what interceptors Spring Security publishes when you add `@EnableMethodSecurity`:
  133. [tabs]
  134. ======
  135. Java::
  136. +
  137. [source,java,role="primary"]
  138. ----
  139. @Bean
  140. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  141. static Advisor preAuthorizeMethodInterceptor() {
  142. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
  143. }
  144. @Bean
  145. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  146. static Advisor postAuthorizeMethodInterceptor() {
  147. return AuthorizationManagerAfterMethodInterceptor.postAuthorize();
  148. }
  149. @Bean
  150. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  151. static Advisor preFilterMethodInterceptor() {
  152. return AuthorizationManagerBeforeMethodInterceptor.preFilter();
  153. }
  154. @Bean
  155. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  156. static Advisor postFilterMethodInterceptor() {
  157. return AuthorizationManagerAfterMethodInterceptor.postFilter();
  158. }
  159. ----
  160. ======
  161. [[favor-granting-authorities]]
  162. === Favor Granting Authorities Over Complicated SpEL Expressions
  163. Quite often it can be tempting to introduce a complicated SpEL expression like the following:
  164. [tabs]
  165. ======
  166. Java::
  167. +
  168. [source,java,role="primary"]
  169. ----
  170. @PreAuthorize("hasAuthority('permission:read') || hasRole('ADMIN')")
  171. ----
  172. ======
  173. .Kotlin
  174. [source,kotlin,role="kotlin"]
  175. ----
  176. @PreAuthorize("hasAuthority('permission:read') || hasRole('ADMIN')")
  177. ----
  178. However, you could instead grant `permission:read` to those with `ROLE_ADMIN`.
  179. One way to do this is with a `RoleHierarchy` like so:
  180. [tabs]
  181. ======
  182. Java::
  183. +
  184. [source,java,role="primary"]
  185. ----
  186. @Bean
  187. static RoleHierarchy roleHierarchy() {
  188. return new RoleHierarchyImpl("ROLE_ADMIN > permission:read");
  189. }
  190. ----
  191. Kotlin::
  192. +
  193. [source,java,role="secondary"]
  194. ----
  195. companion object {
  196. @Bean
  197. fun roleHierarchy(): RoleHierarchy {
  198. return RoleHierarchyImpl("ROLE_ADMIN > permission:read")
  199. }
  200. }
  201. ----
  202. Xml::
  203. +
  204. [source,xml,role="secondary"]
  205. ----
  206. <bean id="roleHierarchy" class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
  207. <constructor-arg value="ROLE_ADMIN > permission:read"/>
  208. </bean>
  209. ----
  210. ======
  211. and then <<customizing-expression-handling,set that in a `MethodSecurityExpressionHandler` instance>>.
  212. This then allows you to have a simpler <<use-preauthorize,`@PreAuthorize`>> expression like this one:
  213. [tabs]
  214. ======
  215. Java::
  216. +
  217. [source,java,role="primary"]
  218. ----
  219. @PreAuthorize("hasAuthority('permission:read')")
  220. ----
  221. Kotlin::
  222. +
  223. [source,kotlin,role="secondary"]
  224. ----
  225. @PreAuthorize("hasAuthority('permission:read')")
  226. ----
  227. ======
  228. Or, where possible, adapt application-specific authorization logic into granted authorities at login time.
  229. [[request-vs-method]]
  230. == Comparing Request-level vs Method-level Authorization
  231. When should you favor method-level authorization over xref:servlet/authorization/authorize-http-requests.adoc[request-level authorization]?
  232. Some of it comes down to taste; however, consider the following strengths list of each to help you decide.
  233. |===
  234. || *request-level* | *method-level*
  235. | *authorization type* | coarse-grained | fine-grained
  236. | *configuration location* | declared in a config class | local to method declaration
  237. | *configuration style* | DSL | Annotations
  238. | *authorization definitions* | programmatic | SpEL
  239. |===
  240. The main tradeoff seems to be where you want your authorization rules to live.
  241. [NOTE]
  242. It's important to remember that when you use annotation-based Method Security, then unannotated methods are not secured.
  243. To protect against this, declare xref:servlet/authorization/authorize-http-requests.adoc#activate-request-security[a catch-all authorization rule] in your xref:servlet/configuration/java.adoc#jc-httpsecurity[`HttpSecurity`] instance.
  244. [[authorizing-with-annotations]]
  245. == Authorizing with Annotations
  246. The primary way Spring Security enables method-level authorization support is through annotations that you can add to methods, classes, and interfaces.
  247. [[use-preauthorize]]
  248. === Authorizing Method Invocation with `@PreAuthorize`
  249. When <<activate-method-security,Method Security is active>>, you can annotate a method with the {security-api-url}org/springframework/security/access/prepost/PreAuthorize.html[`@PreAuthorize`] annotation like so:
  250. [tabs]
  251. ======
  252. Java::
  253. +
  254. [source,java,role="primary"]
  255. ----
  256. @Component
  257. public class BankService {
  258. @PreAuthorize("hasRole('ADMIN')")
  259. public Account readAccount(Long id) {
  260. // ... is only invoked if the `Authentication` has the `ROLE_ADMIN` authority
  261. }
  262. }
  263. ----
  264. Kotlin::
  265. +
  266. [source,kotlin,role="secondary"]
  267. ----
  268. @Component
  269. open class BankService {
  270. @PreAuthorize("hasRole('ADMIN')")
  271. fun readAccount(val id: Long): Account {
  272. // ... is only invoked if the `Authentication` has the `ROLE_ADMIN` authority
  273. }
  274. }
  275. ----
  276. ======
  277. This is meant to indicate that the method can only be invoked if the provided expression `hasRole('ADMIN')` passes.
  278. You can then xref:servlet/test/method.adoc[test the class] to confirm it is enforcing the authorization rule like so:
  279. [tabs]
  280. ======
  281. Java::
  282. +
  283. [source,java,role="primary"]
  284. ----
  285. @Autowired
  286. BankService bankService;
  287. @WithMockUser(roles="ADMIN")
  288. @Test
  289. void readAccountWithAdminRoleThenInvokes() {
  290. Account account = this.bankService.readAccount("12345678");
  291. // ... assertions
  292. }
  293. @WithMockUser(roles="WRONG")
  294. @Test
  295. void readAccountWithWrongRoleThenAccessDenied() {
  296. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(
  297. () -> this.bankService.readAccount("12345678"));
  298. }
  299. ----
  300. Kotlin::
  301. +
  302. [source,kotlin,role="secondary"]
  303. ----
  304. @WithMockUser(roles="ADMIN")
  305. @Test
  306. fun readAccountWithAdminRoleThenInvokes() {
  307. val account: Account = this.bankService.readAccount("12345678")
  308. // ... assertions
  309. }
  310. @WithMockUser(roles="WRONG")
  311. @Test
  312. fun readAccountWithWrongRoleThenAccessDenied() {
  313. assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy {
  314. this.bankService.readAccount("12345678")
  315. }
  316. }
  317. ----
  318. ======
  319. [TIP]
  320. `@PreAuthorize` also can be a <<meta-annotations, meta-annotation>>, be defined <<class-or-interface-annotations,at the class or interface level>>, and use <<authorization-expressions, SpEL Authorization Expressions>>.
  321. While `@PreAuthorize` is quite helpful for declaring needed authorities, it can also be used to evaluate more complex <<using_method_parameters,expressions that involve the method parameters>>.
  322. The above two snippets are ensuring that the user can only request orders that belong to them by comparing the username parameter to xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication#getName`].
  323. The result is that the above method will only be invoked if the `username` in the request path matches the logged-in user's `name`.
  324. If not, Spring Security will throw an `AccessDeniedException` and return a 403 status code.
  325. [[use-postauthorize]]
  326. === Authorization Method Results with `@PostAuthorize`
  327. When Method Security is active, you can annotate a method with the {security-api-url}org/springframework/security/access/prepost/PostAuthorize.html[`@PostAuthorize`] annotation like so:
  328. [tabs]
  329. ======
  330. Java::
  331. +
  332. [source,java,role="primary"]
  333. ----
  334. @Component
  335. public class BankService {
  336. @PostAuthorize("returnObject.owner == authentication.name")
  337. public Account readAccount(Long id) {
  338. // ... is only returned if the `Account` belongs to the logged in user
  339. }
  340. }
  341. ----
  342. Kotlin::
  343. +
  344. [source,kotlin,role="secondary"]
  345. ----
  346. @Component
  347. open class BankService {
  348. @PostAuthorize("returnObject.owner == authentication.name")
  349. fun readAccount(val id: Long): Account {
  350. // ... is only returned if the `Account` belongs to the logged in user
  351. }
  352. }
  353. ----
  354. ======
  355. This is meant to indicate that the method can only return the value if the provided expression `returnObject.owner == authentication.name` passes.
  356. `returnObject` represents the `Account` object to be returned.
  357. You can then xref:servlet/test/method.adoc[test the class] to confirm it is enforcing the authorization rule:
  358. [tabs]
  359. ======
  360. Java::
  361. +
  362. [source,java,role="primary"]
  363. ----
  364. @Autowired
  365. BankService bankService;
  366. @WithMockUser(username="owner")
  367. @Test
  368. void readAccountWhenOwnedThenReturns() {
  369. Account account = this.bankService.readAccount("12345678");
  370. // ... assertions
  371. }
  372. @WithMockUser(username="wrong")
  373. @Test
  374. void readAccountWhenNotOwnedThenAccessDenied() {
  375. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(
  376. () -> this.bankService.readAccount("12345678"));
  377. }
  378. ----
  379. Kotlin::
  380. +
  381. [source,kotlin,role="secondary"]
  382. ----
  383. @WithMockUser(username="owner")
  384. @Test
  385. fun readAccountWhenOwnedThenReturns() {
  386. val account: Account = this.bankService.readAccount("12345678")
  387. // ... assertions
  388. }
  389. @WithMockUser(username="wrong")
  390. @Test
  391. fun readAccountWhenNotOwnedThenAccessDenied() {
  392. assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy {
  393. this.bankService.readAccount("12345678")
  394. }
  395. }
  396. ----
  397. ======
  398. [TIP]
  399. `@PostAuthorize` also can be a <<meta-annotations,meta-annotation>>, be defined <<class-or-interface-annotations,at the class or interface level>>, and use <<authorization-expressions, SpEL Authorization Expressions>>.
  400. `@PostAuthorize` is particularly helpful when defending against https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html[Insecure Direct Object Reference].
  401. In fact, it can be defined as a <<meta-annotations,meta-annotation>> like so:
  402. [tabs]
  403. ======
  404. Java::
  405. +
  406. [source,java,role="primary"]
  407. ----
  408. @Target({ ElementType.METHOD, ElementType.TYPE })
  409. @Retention(RetentionPolicy.RUNTIME)
  410. @PostAuthorize("returnObject.owner == authentication.name")
  411. public @interface RequireOwnership {}
  412. ----
  413. Kotlin::
  414. +
  415. [source,kotlin,role="secondary"]
  416. ----
  417. @Target(ElementType.METHOD, ElementType.TYPE)
  418. @Retention(RetentionPolicy.RUNTIME)
  419. @PostAuthorize("returnObject.owner == authentication.name")
  420. annotation class RequireOwnership
  421. ----
  422. ======
  423. Allowing you to instead annotate the service in the following way:
  424. [tabs]
  425. ======
  426. Java::
  427. +
  428. [source,java,role="primary"]
  429. ----
  430. @Component
  431. public class BankService {
  432. @RequireOwnership
  433. public Account readAccount(Long id) {
  434. // ... is only returned if the `Account` belongs to the logged in user
  435. }
  436. }
  437. ----
  438. Kotlin::
  439. +
  440. [source,kotlin,role="secondary"]
  441. ----
  442. @Component
  443. open class BankService {
  444. @RequireOwnership
  445. fun readAccount(val id: Long): Account {
  446. // ... is only returned if the `Account` belongs to the logged in user
  447. }
  448. }
  449. ----
  450. ======
  451. The result is that the above method will only return the `Account` if its `owner` attribute matches the logged-in user's `name`.
  452. If not, Spring Security will throw an `AccessDeniedException` and return a 403 status code.
  453. [[use-prefilter]]
  454. === Filtering Method Parameters with `@PreFilter`
  455. [NOTE]
  456. `@PreFilter` is not yet supported for Kotlin-specific data types; for that reason, only Java snippets are shown
  457. When Method Security is active, you can annotate a method with the {security-api-url}org/springframework/security/access/prepost/PreFilter.html[`@PreFilter`] annotation like so:
  458. [tabs]
  459. ======
  460. Java::
  461. +
  462. [source,java,role="primary"]
  463. ----
  464. @Component
  465. public class BankService {
  466. @PreFilter("filterObject.owner == authentication.name")
  467. public Collection<Account> updateAccounts(Account... accounts) {
  468. // ... `accounts` will only contain the accounts owned by the logged-in user
  469. return updated;
  470. }
  471. }
  472. ----
  473. ======
  474. This is meant to filter out any values from `accounts` where the expression `filterObject.owner == authentication.name` fails.
  475. `filterObject` represents each `account` in `accounts` and is used to test each `account`.
  476. You can then test the class in the following way to confirm it is enforcing the authorization rule:
  477. [tabs]
  478. ======
  479. Java::
  480. +
  481. [source,java,role="primary"]
  482. ----
  483. @Autowired
  484. BankService bankService;
  485. @WithMockUser(username="owner")
  486. @Test
  487. void updateAccountsWhenOwnedThenReturns() {
  488. Account ownedBy = ...
  489. Account notOwnedBy = ...
  490. Collection<Account> updated = this.bankService.updateAccounts(ownedBy, notOwnedBy);
  491. assertThat(updated).containsOnly(ownedBy);
  492. }
  493. ----
  494. ======
  495. [TIP]
  496. `@PreFilter` also can be a <<meta-annotations,meta-annotation>>, be defined <<class-or-interface-annotations,at the class or interface level>>, and use <<authorization-expressions, SpEL Authorization Expressions>>.
  497. `@PreFilter` supports arrays, collections, maps, and streams (so long as the stream is still open).
  498. For example, the above `updateAccounts` declaration will function the same way as the following other four:
  499. [tabs]
  500. ======
  501. Java::
  502. +
  503. [source,java,role="primary"]
  504. ----
  505. @PreFilter("filterObject.owner == authentication.name")
  506. public Collection<Account> updateAccounts(Account[] accounts)
  507. @PreFilter("filterObject.owner == authentication.name")
  508. public Collection<Account> updateAccounts(Collection<Account> accounts)
  509. @PreFilter("filterObject.value.owner == authentication.name")
  510. public Collection<Account> updateAccounts(Map<String, Account> accounts)
  511. @PreFilter("filterObject.owner == authentication.name")
  512. public Collection<Account> updateAccounts(Stream<Account> accounts)
  513. ----
  514. ======
  515. The result is that the above method will only have the `Account` instances where their `owner` attribute matches the logged-in user's `name`.
  516. [[use-postfilter]]
  517. === Filtering Method Results with `@PostFilter`
  518. [NOTE]
  519. `@PostFilter` is not yet supported for Kotlin-specific data types; for that reason, only Java snippets are shown
  520. When Method Security is active, you can annotate a method with the {security-api-url}org/springframework/security/access/prepost/PostFilter.html[`@PostFilter`] annotation like so:
  521. [tabs]
  522. ======
  523. Java::
  524. +
  525. [source,java,role="primary"]
  526. ----
  527. @Component
  528. public class BankService {
  529. @PostFilter("filterObject.owner == authentication.name")
  530. public Collection<Account> readAccounts(String... ids) {
  531. // ... the return value will be filtered to only contain the accounts owned by the logged-in user
  532. return accounts;
  533. }
  534. }
  535. ----
  536. ======
  537. This is meant to filter out any values from the return value where the expression `filterObject.owner == authentication.name` fails.
  538. `filterObject` represents each `account` in `accounts` and is used to test each `account`.
  539. You can then test the class like so to confirm it is enforcing the authorization rule:
  540. [tabs]
  541. ======
  542. Java::
  543. +
  544. [source,java,role="primary"]
  545. ----
  546. @Autowired
  547. BankService bankService;
  548. @WithMockUser(username="owner")
  549. @Test
  550. void readAccountsWhenOwnedThenReturns() {
  551. Collection<Account> accounts = this.bankService.updateAccounts("owner", "not-owner");
  552. assertThat(accounts).hasSize(1);
  553. assertThat(accounts.get(0).getOwner()).isEqualTo("owner");
  554. }
  555. ----
  556. ======
  557. [TIP]
  558. `@PostFilter` also can be a <<meta-annotations,meta-annotation>>, be defined <<class-or-interface-annotations,at the class or interface level>>, and use <<authorization-expressions, SpEL Authorization Expressions>>.
  559. `@PostFilter` supports arrays, collections, maps, and streams (so long as the stream is still open).
  560. For example, the above `readAccounts` declaration will function the same way as the following other three:
  561. ```java
  562. @PostFilter("filterObject.owner == authentication.name")
  563. public Account[] readAccounts(String... ids)
  564. @PostFilter("filterObject.value.owner == authentication.name")
  565. public Map<String, Account> readAccounts(String... ids)
  566. @PostFilter("filterObject.owner == authentication.name")
  567. public Stream<Account> readAccounts(String... ids)
  568. ```
  569. The result is that the above method will return the `Account` instances where their `owner` attribute matches the logged-in user's `name`.
  570. [NOTE]
  571. In-memory filtering can obviously be expensive, and so be considerate of whether it is better to xref:servlet/integrations/data.adoc[filter the data in the data layer] instead.
  572. [[use-secured]]
  573. === Authorizing Method Invocation with `@Secured`
  574. {security-api-url}org/springframework/security/access/annotation/Secured.html[`@Secured`] is a legacy option for authorizing invocations.
  575. <<use-preauthorize,`@PreAuthorize`>> supercedes it and is recommended instead.
  576. To use the `@Secured` annotation, you should first change your Method Security declaration to enable it like so:
  577. [tabs]
  578. ======
  579. Java::
  580. +
  581. [source,java,role="primary"]
  582. ----
  583. @EnableMethodSecurity(securedEnabled = true)
  584. ----
  585. Kotlin::
  586. +
  587. [source,kotlin,role="secondary"]
  588. ----
  589. @EnableMethodSecurity(securedEnabled = true)
  590. ----
  591. Xml::
  592. +
  593. [source,xml,role="secondary"]
  594. ----
  595. <sec:method-security secured-enabled="true"/>
  596. ----
  597. ======
  598. This will cause Spring Security to publish <<annotation-method-interceptors,the corresponding method interceptor>> that authorizes methods, classes, and interfaces annotated with `@Secured`.
  599. [[use-jsr250]]
  600. === Authorizing Method Invocation with JSR-250 Annotations
  601. In case you would like to use https://jcp.org/en/jsr/detail?id=250[JSR-250] annotations, Spring Security also supports that.
  602. <<use-preauthorize,`@PreAuthorize`>> has more expressive power and is thus recommended.
  603. To use the JSR-250 annotations, you should first change your Method Security declaration to enable them like so:
  604. [tabs]
  605. ======
  606. Java::
  607. +
  608. [source,java,role="primary"]
  609. ----
  610. @EnableMethodSecurity(jsr250Enabled = true)
  611. ----
  612. Kotlin::
  613. +
  614. [source,kotlin,role="secondary"]
  615. ----
  616. @EnableMethodSecurity(jsr250Enabled = true)
  617. ----
  618. Xml::
  619. +
  620. [source,xml,role="secondary"]
  621. ----
  622. <sec:method-security jsr250-enabled="true"/>
  623. ----
  624. ======
  625. This will cause Spring Security to publish <<annotation-method-interceptors,the corresponding method interceptor>> that authorizes methods, classes, and interfaces annotated with `@RolesAllowed`, `@PermitAll`, and `@DenyAll`.
  626. [[class-or-interface-annotations]]
  627. === Declaring Annotations at the Class or Interface Level
  628. It's also supported to have Method Security annotations at the class and interface level.
  629. If it is at the class level like so:
  630. [tabs]
  631. ======
  632. Java::
  633. +
  634. [source,java,role="primary"]
  635. ----
  636. @Controller
  637. @PreAuthorize("hasAuthority('ROLE_USER')")
  638. public class MyController {
  639. @GetMapping("/endpoint")
  640. public String endpoint() { ... }
  641. }
  642. ----
  643. Kotlin::
  644. +
  645. [source,kotlin,role="secondary"]
  646. ----
  647. @Controller
  648. @PreAuthorize("hasAuthority('ROLE_USER')")
  649. open class MyController {
  650. @GetMapping("/endpoint")
  651. fun endpoint(): String { ... }
  652. }
  653. ----
  654. ======
  655. then all methods inherit the class-level behavior.
  656. Or, if it's declared like the following at both the class and method level:
  657. [tabs]
  658. ======
  659. Java::
  660. +
  661. [source,java,role="primary"]
  662. ----
  663. @Controller
  664. @PreAuthorize("hasAuthority('ROLE_USER')")
  665. public class MyController {
  666. @GetMapping("/endpoint")
  667. @PreAuthorize("hasAuthority('ROLE_ADMIN')")
  668. public String endpoint() { ... }
  669. }
  670. ----
  671. Kotlin::
  672. +
  673. [source,kotlin,role="secondary"]
  674. ----
  675. @Controller
  676. @PreAuthorize("hasAuthority('ROLE_USER')")
  677. open class MyController {
  678. @GetMapping("/endpoint")
  679. @PreAuthorize("hasAuthority('ROLE_ADMIN')")
  680. fun endpoint(): String { ... }
  681. }
  682. ----
  683. ======
  684. then methods declaring the annotation override the class-level annotation.
  685. The same is true for interfaces, with the exception that if a class inherits the annotation from two different interfaces, then startup will fail.
  686. This is because Spring Security has no way to tell which one you want to use.
  687. In cases like this, you can resolve the ambiguity by adding the annotation to the concrete method.
  688. [[meta-annotations]]
  689. === Using Meta Annotations
  690. Method Security supports meta annotations.
  691. This means that you can take any annotation and improve readability based on your application-specific use cases.
  692. For example, you can simplify `@PreAuthorize("hasRole('ADMIN')")` to `@IsAdmin` like so:
  693. [tabs]
  694. ======
  695. Java::
  696. +
  697. [source,java,role="primary"]
  698. ----
  699. @Target({ ElementType.METHOD, ElementType.TYPE })
  700. @Retention(RetentionPolicy.RUNTIME)
  701. @PreAuthorize("hasRole('ADMIN')")
  702. public @interface IsAdmin {}
  703. ----
  704. Kotlin::
  705. +
  706. [source,kotlin,role="secondary"]
  707. ----
  708. @Target(ElementType.METHOD, ElementType.TYPE)
  709. @Retention(RetentionPolicy.RUNTIME)
  710. @PreAuthorize("hasRole('ADMIN')")
  711. annotation class IsAdmin
  712. ----
  713. ======
  714. And the result is that on your secured methods you can now do the following instead:
  715. [tabs]
  716. ======
  717. Java::
  718. +
  719. [source,java,role="primary"]
  720. ----
  721. @Component
  722. public class BankService {
  723. @IsAdmin
  724. public Account readAccount(Long id) {
  725. // ... is only returned if the `Account` belongs to the logged in user
  726. }
  727. }
  728. ----
  729. Kotlin::
  730. +
  731. [source,kotlin,role="secondary"]
  732. ----
  733. @Component
  734. open class BankService {
  735. @IsAdmin
  736. fun readAccount(val id: Long): Account {
  737. // ... is only returned if the `Account` belongs to the logged in user
  738. }
  739. }
  740. ----
  741. ======
  742. This results in more readable method definitions.
  743. [[enable-annotation]]
  744. === Enabling Certain Annotations
  745. You can turn off ``@EnableMethodSecurity``'s pre-configuration and replace it with you own.
  746. You may choose to do this if you want to <<custom-authorization-managers,customize the `AuthorizationManager`>> or `Pointcut`.
  747. Or you may simply want to only enable a specific annotation, like `@PostAuthorize`.
  748. You can do this in the following way:
  749. .Only @PostAuthorize Configuration
  750. [tabs]
  751. ======
  752. Java::
  753. +
  754. [source,java,role="primary"]
  755. ----
  756. @Configuration
  757. @EnableMethodSecurity(prePostEnabled = false)
  758. class MethodSecurityConfig {
  759. @Bean
  760. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  761. Advisor postAuthorize() {
  762. return AuthorizationManagerBeforeMethodInterceptor.postAuthorize();
  763. }
  764. }
  765. ----
  766. Kotlin::
  767. +
  768. [source,kotlin,role="secondary"]
  769. ----
  770. @Configuration
  771. @EnableMethodSecurity(prePostEnabled = false)
  772. class MethodSecurityConfig {
  773. @Bean
  774. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  775. fun postAuthorize() : Advisor {
  776. return AuthorizationManagerBeforeMethodInterceptor.postAuthorize()
  777. }
  778. }
  779. ----
  780. Xml::
  781. +
  782. [source,xml,role="secondary"]
  783. ----
  784. <sec:method-security pre-post-enabled="false"/>
  785. <aop:config/>
  786. <bean id="postAuthorize"
  787. class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor"
  788. factory-method="postAuthorize"/>
  789. ----
  790. ======
  791. The above snippet achieves this by first disabling Method Security's pre-configurations and then publishing <<annotation-method-interceptors, the `@PostAuthorize` interceptor>> itself.
  792. [[use-intercept-methods]]
  793. == Authorizing with `<intercept-methods>`
  794. While using Spring Security's <<authorizing-with-annotations,annotation-based support>> is preferred for method security, you can also use XML to declare bean authorization rules.
  795. If you need to declare it in your XML configuration instead, you can use xref:servlet/appendix/namespace/method-security.adoc#nsa-intercept-methods[`<intercept-methods>`] like so:
  796. [tabs]
  797. ======
  798. Xml::
  799. +
  800. [source,xml,role="primary"]
  801. ----
  802. <bean class="org.mycompany.MyController">
  803. <intercept-methods>
  804. <protect method="get*" access="hasAuthority('read')"/>
  805. <protect method="*" access="hasAuthority('write')"/>
  806. </intercept-methods>
  807. </bean>
  808. ----
  809. ======
  810. [NOTE]
  811. This only supports matching method by prefix or by name.
  812. If your needs are more complex than that, <<authorizing-with-annotations,use annotation support>> instead.
  813. [[use-programmatic-authorization]]
  814. == Authorizing Methods Programmatically
  815. As you've already seen, there are several ways that you can specify non-trivial authorization rules using <<authorization-expressions, Method Security SpEL expressions>>.
  816. There are a number of ways that you can instead allow your logic to be Java-based instead of SpEL-based.
  817. This gives use access the entire Java language for increased testability and flow control.
  818. === Using a Custom Bean in SpEL
  819. The first way to authorize a method programmatically is a two-step process.
  820. First, declare a bean that has a method that takes a `MethodSecurityExpressionOperations` instance like the following:
  821. [tabs]
  822. ======
  823. Java::
  824. +
  825. [source,java,role="primary"]
  826. ----
  827. @Component("authz")
  828. public class AuthorizationLogic {
  829. public boolean decide(MethodSecurityExpressionOperations operations) {
  830. // ... authorization logic
  831. }
  832. }
  833. ----
  834. Kotlin::
  835. +
  836. [source,kotlin,role="secondary"]
  837. ----
  838. @Component("authz")
  839. open class AuthorizationLogic {
  840. fun decide(val operations: MethodSecurityExpressionOperations): boolean {
  841. // ... authorization logic
  842. }
  843. }
  844. ----
  845. ======
  846. Then, reference that bean in your annotations in the following way:
  847. [tabs]
  848. ======
  849. Java::
  850. +
  851. [source,java,role="primary"]
  852. ----
  853. @Controller
  854. public class MyController {
  855. @PreAuthorize("@authz.decide(#root)")
  856. @GetMapping("/endpoint")
  857. public String endpoint() {
  858. // ...
  859. }
  860. }
  861. ----
  862. Kotlin::
  863. +
  864. [source,kotlin,role="secondary"]
  865. ----
  866. @Controller
  867. open class MyController {
  868. @PreAuthorize("@authz.decide(#root)")
  869. @GetMapping("/endpoint")
  870. fun String endpoint() {
  871. // ...
  872. }
  873. }
  874. ----
  875. ======
  876. Spring Security will invoke the given method on that bean for each method invocation.
  877. What's nice about this is all your authorization logic is in a separate class that can be independently unit tested and verified for correctness.
  878. It also has access to the full Java language.
  879. [[custom-authorization-managers]]
  880. === Using a Custom Authorization Manager
  881. The second way to authorize a method programmatically is to create a custom xref:servlet/authorization/architecture.adoc#_the_authorizationmanager[`AuthorizationManager`].
  882. First, declare an authorization manager instance, perhaps like this one:
  883. [tabs]
  884. ======
  885. Java::
  886. +
  887. [source,java,role="primary"]
  888. ----
  889. @Component
  890. public class MyAuthorizationManager implements AuthorizationManager<MethodInvocation>, AuthorizationManager<MethodInvocationResult> {
  891. @Override
  892. public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocation invocation) {
  893. // ... authorization logic
  894. }
  895. @Override
  896. public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocationResult invocation) {
  897. // ... authorization logic
  898. }
  899. }
  900. ----
  901. Kotlin::
  902. +
  903. [source,kotlin,role="secondary"]
  904. ----
  905. @Component
  906. class MyAuthorizationManager : AuthorizationManager<MethodInvocation>, AuthorizationManager<MethodInvocationResult> {
  907. override fun check(authentication: Supplier<Authentication>, invocation: MethodInvocation): AuthorizationDecision {
  908. // ... authorization logic
  909. }
  910. override fun check(authentication: Supplier<Authentication>, invocation: MethodInvocationResult): AuthorizationDecision {
  911. // ... authorization logic
  912. }
  913. }
  914. ----
  915. ======
  916. Then, publish the method interceptor with a pointcut that corresponds to when you want that `AuthorizationManager` to run.
  917. For example, you could replace how `@PreAuthorize` and `@PostAuthorize` work like so:
  918. .Only @PreAuthorize and @PostAuthorize Configuration
  919. [tabs]
  920. ======
  921. Java::
  922. +
  923. [source,java,role="primary"]
  924. ----
  925. @Configuration
  926. @EnableMethodSecurity(prePostEnabled = false)
  927. class MethodSecurityConfig {
  928. @Bean
  929. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  930. Advisor preAuthorize(MyAuthorizationManager manager) {
  931. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(manager);
  932. }
  933. @Bean
  934. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  935. Advisor postAuthorize(MyAuthorizationManager manager) {
  936. return AuthorizationManagerAfterMethodInterceptor.postAuthorize(manager);
  937. }
  938. }
  939. ----
  940. Kotlin::
  941. +
  942. [source,kotlin,role="secondary"]
  943. ----
  944. @Configuration
  945. @EnableMethodSecurity(prePostEnabled = false)
  946. class MethodSecurityConfig {
  947. @Bean
  948. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  949. fun preAuthorize(val manager: MyAuthorizationManager) : Advisor {
  950. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(manager)
  951. }
  952. @Bean
  953. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  954. fun postAuthorize(val manager: MyAuthorizationManager) : Advisor {
  955. return AuthorizationManagerAfterMethodInterceptor.postAuthorize(manager)
  956. }
  957. }
  958. ----
  959. Xml::
  960. +
  961. [source,xml,role="secondary"]
  962. ----
  963. <sec:method-security pre-post-enabled="false"/>
  964. <aop:config/>
  965. <bean id="preAuthorize"
  966. class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor"
  967. factory-method="preAuthorize">
  968. <constructor-arg ref="myAuthorizationManager"/>
  969. </bean>
  970. <bean id="postAuthorize"
  971. class="org.springframework.security.authorization.method.AuthorizationManagerAfterMethodInterceptor"
  972. factory-method="postAuthorize">
  973. <constructor-arg ref="myAuthorizationManager"/>
  974. </bean>
  975. ----
  976. ======
  977. [TIP]
  978. ====
  979. You can place your interceptor in between Spring Security method interceptors using the order constants specified in `AuthorizationInterceptorsOrder`.
  980. ====
  981. [[customizing-expression-handling]]
  982. === Customizing Expression Handling
  983. Or, third, you can customize how each SpEL expression is handled.
  984. To do that, you can expose a custom {security-api-url}org.springframework.security.access.expression.method.MethodSecurityExpressionHandler.html[`MethodSecurityExpressionHandler`], like so:
  985. .Custom MethodSecurityExpressionHandler
  986. [tabs]
  987. ======
  988. Java::
  989. +
  990. [source,java,role="primary"]
  991. ----
  992. @Bean
  993. static MethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) {
  994. DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
  995. handler.setRoleHierarchy(roleHierarchy);
  996. return handler;
  997. }
  998. ----
  999. Kotlin::
  1000. +
  1001. [source,kotlin,role="secondary"]
  1002. ----
  1003. companion object {
  1004. @Bean
  1005. fun methodSecurityExpressionHandler(val roleHierarchy: RoleHierarchy) : MethodSecurityExpressionHandler {
  1006. val handler = DefaultMethodSecurityExpressionHandler();
  1007. handler.setRoleHierarchy(roleHierarchy);
  1008. return handler;
  1009. }
  1010. }
  1011. ----
  1012. Xml::
  1013. +
  1014. [source,xml,role="secondary"]
  1015. ----
  1016. <sec:method-security>
  1017. <sec:expression-handler ref="myExpressionHandler"/>
  1018. </sec:method-security>
  1019. <bean id="myExpressionHandler"
  1020. class="org.springframework.security.messaging.access.expression.DefaultMessageSecurityExpressionHandler">
  1021. <property name="roleHierarchy" ref="roleHierarchy"/>
  1022. </bean>
  1023. ----
  1024. ======
  1025. [TIP]
  1026. ====
  1027. We expose `MethodSecurityExpressionHandler` using a `static` method to ensure that Spring publishes it before it initializes Spring Security's method security `@Configuration` classes
  1028. ====
  1029. You can also <<subclass-defaultmethodsecurityexpressionhandler,subclass `DefaultMessageSecurityExpressionHandler`>> to add your own custom authorization expressions beyond the defaults.
  1030. [[use-aspectj]]
  1031. == Authorizing with AspectJ
  1032. [[match-by-pointcut]]
  1033. === Matching Methods with Custom Pointcuts
  1034. Being built on Spring AOP, you can declare patterns that are not related to annotations, similar to xref:servlet/authorization/authorize-http-requests.adoc[request-level authorization].
  1035. This has the potential advantage of centralizing method-level authorization rules.
  1036. For example, you can use publish your own `Advisor` or use xref:servlet/appendix/namespace/method-security.adoc#nsa-protect-pointcut[`<protect-pointcut>`] to match AOP expressions to authorization rules for your service layer like so:
  1037. [tabs]
  1038. ======
  1039. Java::
  1040. +
  1041. [source,java,role="primary"]
  1042. ----
  1043. import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole;
  1044. @Bean
  1045. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1046. static Advisor protectServicePointcut() {
  1047. JdkRegexpMethodPointcut pattern = new JdkRegexpMethodPointcut();
  1048. pattern.setPattern("execution(* com.mycompany.*Service.*(..))");
  1049. return new AuthorizationManagerBeforeMethodInterceptor(pattern, hasRole("USER"));
  1050. }
  1051. ----
  1052. Kotlin::
  1053. +
  1054. [source,kotlin,role="secondary"]
  1055. ----
  1056. import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole;
  1057. companion object {
  1058. @Bean
  1059. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1060. fun protectServicePointcut(): Advisor {
  1061. var pattern = JdkRegexpMethodPointcut();
  1062. pattern.setPattern("execution(* com.mycompany.*Service.*(..))");
  1063. return new AuthorizationManagerBeforeMethodInterceptor(pattern, hasRole("USER"));
  1064. }
  1065. }
  1066. ----
  1067. ======
  1068. [source,xml]
  1069. ----
  1070. <sec:method-security>
  1071. <protect-pointcut expression="execution(* com.mycompany.*Service.*(..))" access="hasRole('USER')"/>
  1072. </sec:method-security>
  1073. ----
  1074. [[weave-aspectj]]
  1075. === Integrate with AspectJ Byte-weaving
  1076. Performance can at times be enhanced by using AspectJ to weave Spring Security advice into the byte code of your beans.
  1077. After setting up AspectJ, you can quite simply state in the `@EnableMethodSecurity` annotation or `<method-security>` element that you are using AspectJ:
  1078. [tabs]
  1079. ======
  1080. Java::
  1081. +
  1082. [source,java,role="primary"]
  1083. ----
  1084. @EnableMethodSecurity(mode=AdviceMode.ASPECTJ)
  1085. ----
  1086. Kotlin::
  1087. +
  1088. [source,kotlin,role="secondary"]
  1089. ----
  1090. @EnableMethodSecurity(mode=AdviceMode.ASPECTJ)
  1091. ----
  1092. Xml::
  1093. +
  1094. [source,xml,role="secondary"]
  1095. ----
  1096. <sec:method-security mode="aspectj"/>
  1097. ----
  1098. ======
  1099. And the result will be that Spring Security will publish its advisors as AspectJ advice so that they can be woven in accordingly.
  1100. [[changing-the-order]]
  1101. == Specifying Order
  1102. As already noted, there is a Spring AOP method interceptor for each annotation, and each of these has a location in the Spring AOP advisor chain.
  1103. Namely, the `@PreFilter` method interceptor's order is 100, ``@PreAuthorize``'s is 200, and so on.
  1104. The reason this is important to note is that there are other AOP-based annotations like `@EnableTransactionManagement` that have an order of `Integer.MAX_VALUE`.
  1105. In other words, they are located at the end of the advisor chain by default.
  1106. At times, it can be valuable to have other advice execute before Spring Security.
  1107. For example, if you have a method annotated with `@Transactional` and `@PostAuthorize`, you might want the transaction to still be open when `@PostAuthorize` runs so that an `AccessDeniedException` will cause a rollback.
  1108. To get `@EnableTransactionManagement` to open a transaction before method authorization advice runs, you can set ``@EnableTransactionManagement``'s order like so:
  1109. [tabs]
  1110. ======
  1111. Java::
  1112. +
  1113. [source,java,role="primary"]
  1114. ----
  1115. @EnableTransactionManagement(order = 0)
  1116. ----
  1117. Kotlin::
  1118. +
  1119. [source,kotlin,role="secondary"]
  1120. ----
  1121. @EnableTransactionManagement(order = 0)
  1122. ----
  1123. Xml::
  1124. +
  1125. [source,xml,role="secondary"]
  1126. ----
  1127. <tx:annotation-driven ref="txManager" order="0"/>
  1128. ----
  1129. ======
  1130. Since the earliest method interceptor (`@PreFilter`) is set to an order of 100, a setting of zero means that the transaction advice will run before all Spring Security advice.
  1131. [[authorization-expressions]]
  1132. == Expressing Authorization with SpEL
  1133. You've already seen several examples using SpEL, so now let's cover the API a bit more in depth.
  1134. Spring Security encapsulates all of its authorization fields and methods in a set of root objects.
  1135. The most generic root object is called `SecurityExpressionRoot` and it forms the basis for `MethodSecurityExpressionRoot`.
  1136. Spring Security supplies this root object to `MethodSecurityEvaluationContext` when preparing to evaluate an authorization expression.
  1137. [[using-authorization-expression-fields-and-methods]]
  1138. === Using Authorization Expression Fields and Methods
  1139. The first thing this provides is an enhanced set of authorization fields and methods to your SpEL expressions.
  1140. What follows is a quick overview of the most common methods:
  1141. * `permitAll` - The method requires no authorization to be invoked; note that in this case, xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[the `Authentication`] is never retrieved from the session
  1142. * `denyAll` - The method is not allowed under any circumstances; note that in this case, the `Authentication` is never retrieved from the session
  1143. * `hasAuthority` - The method requires that the `Authentication` have xref:servlet/authorization/architecture.adoc#authz-authorities[a `GrantedAuthority`] that matches the given value
  1144. * `hasRole` - A shortcut for `hasAuthority` that prefixes `ROLE_` or whatever is configured as the default prefix
  1145. * `hasAnyAuthority` - The method requires that the `Authentication` have a `GrantedAuthority` that matches any of the given values
  1146. * `hasAnyRole` - A shortcut for `hasAnyAuthority` that prefixes `ROLE_` or whatever is configured as the default prefix
  1147. * `hasPermission` - A hook into your `PermissionEvaluator` instance for doing object-level authorization
  1148. And here is a brief look at the most common fields:
  1149. * `authentication` - The `Authentication` instance associated with this method invocation
  1150. * `principal` - The `Authentication#getPrincipal` associated with this method invocation
  1151. Having now learned the patterns, rules, and how they can be paired together, you should be able to understand what is going on in this more complex example:
  1152. .Authorize Requests
  1153. [tabs]
  1154. ======
  1155. Java::
  1156. +
  1157. [source,java,role="primary"]
  1158. ----
  1159. @Component
  1160. public class MyService {
  1161. @PreAuthorize("denyAll") <1>
  1162. MyResource myDeprecatedMethod(...);
  1163. @PreAuthorize("hasRole('ADMIN')") <2>
  1164. MyResource writeResource(...)
  1165. @PreAuthorize("hasAuthority('db') and hasRole('ADMIN')") <3>
  1166. MyResource deleteResource(...)
  1167. @PreAuthorize("principal.claims['aud'] == 'my-audience'") <4>
  1168. MyResource readResource(...);
  1169. @PreAuthorize("@authz.check(authentication, #root)")
  1170. MyResource shareResource(...);
  1171. }
  1172. ----
  1173. Kotlin::
  1174. +
  1175. [source,kotlin,role="secondary"]
  1176. ----
  1177. @Component
  1178. open class MyService {
  1179. @PreAuthorize("denyAll") <1>
  1180. fun myDeprecatedMethod(...): MyResource
  1181. @PreAuthorize("hasRole('ADMIN')") <2>
  1182. fun writeResource(...): MyResource
  1183. @PreAuthorize("hasAuthority('db') and hasRole('ADMIN')") <3>
  1184. fun deleteResource(...): MyResource
  1185. @PreAuthorize("principal.claims['aud'] == 'my-audience'") <4>
  1186. fun readResource(...): MyResource
  1187. @PreAuthorize("@authz.check(#root)")
  1188. fun shareResource(...): MyResource;
  1189. }
  1190. ----
  1191. Xml::
  1192. +
  1193. [source,xml,role="secondary"]
  1194. ----
  1195. <sec:method-security>
  1196. <protect-pointcut expression="execution(* com.mycompany.*Service.myDeprecatedMethod(..))" access="denyAll"/> <1>
  1197. <protect-pointcut expression="execution(* com.mycompany.*Service.writeResource(..))" access="hasRole('ADMIN')"/> <2>
  1198. <protect-pointcut expression="execution(* com.mycompany.*Service.deleteResource(..))" access="hasAuthority('db') and hasRole('ADMIN')"/> <3>
  1199. <protect-pointcut expression="execution(* com.mycompany.*Service.readResource(..))" access="principal.claims['aud'] == 'my-audience'"/> <4>
  1200. <protect-pointcut expression="execution(* com.mycompany.*Service.shareResource(..))" access="@authz.check(#root)"/> <5>
  1201. </sec:method-security>
  1202. ----
  1203. ======
  1204. <1> This method may not be invoked by anyone for any reason
  1205. <2> This method may only be invoked by ``Authentication``s granted the `ROLE_ADMIN` authority
  1206. <3> This method may only be invoked by ``Authentication``s granted the `db` and `ROLE_ADMIN` authorities
  1207. <4> This method may only be invoked by ``Princpal``s with an `aud` claim equal to "my-audience"
  1208. <5> This method may only be invoked if the bean ``authz``'s `check` method returns `true`
  1209. [[using_method_parameters]]
  1210. === Using Method Parameters
  1211. Additionally, Spring Security provides a mechanism for discovering method parameters so they can also be accessed in the SpEL expression as well.
  1212. For a complete reference, Spring Security uses `DefaultSecurityParameterNameDiscoverer` to discover the parameter names.
  1213. By default, the following options are tried for a method.
  1214. 1. If Spring Security's `@P` annotation is present on a single argument to the method, the value is used.
  1215. The following example uses the `@P` annotation:
  1216. +
  1217. [tabs]
  1218. ======
  1219. Java::
  1220. +
  1221. [source,java,role="primary"]
  1222. ----
  1223. import org.springframework.security.access.method.P;
  1224. ...
  1225. @PreAuthorize("hasPermission(#c, 'write')")
  1226. public void updateContact(@P("c") Contact contact);
  1227. ----
  1228. Kotlin::
  1229. +
  1230. [source,kotlin,role="secondary"]
  1231. ----
  1232. import org.springframework.security.access.method.P
  1233. ...
  1234. @PreAuthorize("hasPermission(#c, 'write')")
  1235. fun doSomething(@P("c") contact: Contact?)
  1236. ----
  1237. ======
  1238. +
  1239. The intention of this expression is to require that the current `Authentication` have `write` permission specifically for this `Contact` instance.
  1240. +
  1241. Behind the scenes, this is implemented by using `AnnotationParameterNameDiscoverer`, which you can customize to support the value attribute of any specified annotation.
  1242. * If xref:servlet/integrations/data.adoc[Spring Data's] `@Param` annotation is present on at least one parameter for the method, the value is used.
  1243. The following example uses the `@Param` annotation:
  1244. +
  1245. [tabs]
  1246. ======
  1247. Java::
  1248. +
  1249. [source,java,role="primary"]
  1250. ----
  1251. import org.springframework.data.repository.query.Param;
  1252. ...
  1253. @PreAuthorize("#n == authentication.name")
  1254. Contact findContactByName(@Param("n") String name);
  1255. ----
  1256. Kotlin::
  1257. +
  1258. [source,kotlin,role="secondary"]
  1259. ----
  1260. import org.springframework.data.repository.query.Param
  1261. ...
  1262. @PreAuthorize("#n == authentication.name")
  1263. fun findContactByName(@Param("n") name: String?): Contact?
  1264. ----
  1265. ======
  1266. +
  1267. The intention of this expression is to require that `name` be equal to `Authentication#getName` for the invocation to be authorized.
  1268. +
  1269. Behind the scenes, this is implemented by using `AnnotationParameterNameDiscoverer`, which you can customize to support the value attribute of any specified annotation.
  1270. * If you compile your code with the `-parameters` argument, the standard JDK reflection API is used to discover the parameter names.
  1271. This works on both classes and interfaces.
  1272. * Finally, if you compile your code with debug symbols, the parameter names are discovered by using the debug symbols.
  1273. This does not work for interfaces, since they do not have debug information about the parameter names.
  1274. For interfaces, either annotations or the `-parameters` approach must be used.
  1275. [[migration-enableglobalmethodsecurity]]
  1276. == Migrating from `@EnableGlobalMethodSecurity`
  1277. If you are using `@EnableGlobalMethodSecurity`, you should migrate to `@EnableMethodSecurity`.
  1278. [[servlet-replace-globalmethodsecurity-with-methodsecurity]]
  1279. === Replace xref:servlet/authorization/method-security.adoc#jc-enable-global-method-security[global method security] with xref:servlet/authorization/method-security.adoc#jc-enable-method-security[method security]
  1280. {security-api-url}org/springframework/security/config/annotation/method/configuration/EnableGlobalMethodSecurity.html[`@EnableGlobalMethodSecurity`] and xref:servlet/appendix/namespace/method-security.adoc#nsa-global-method-security[`<global-method-security>`] are deprecated in favor of {security-api-url}org/springframework/security/config/annotation/method/configuration/EnableMethodSecurity.html[`@EnableMethodSecurity`] and xref:servlet/appendix/namespace/method-security.adoc#nsa-method-security[`<method-security>`], respectively.
  1281. The new annotation and XML element activate Spring's xref:servlet/authorization/method-security.adoc#jc-enable-method-security[pre-post annotations] by default and use `AuthorizationManager` internally.
  1282. This means that the following two listings are functionally equivalent:
  1283. [tabs]
  1284. ======
  1285. Java::
  1286. +
  1287. [source,java,role="primary"]
  1288. ----
  1289. @EnableGlobalMethodSecurity(prePostEnabled = true)
  1290. ----
  1291. Kotlin::
  1292. +
  1293. [source,kotlin,role="secondary"]
  1294. ----
  1295. @EnableGlobalMethodSecurity(prePostEnabled = true)
  1296. ----
  1297. Xml::
  1298. +
  1299. [source,xml,role="secondary"]
  1300. ----
  1301. <global-method-security pre-post-enabled="true"/>
  1302. ----
  1303. ======
  1304. and:
  1305. [tabs]
  1306. ======
  1307. Java::
  1308. +
  1309. [source,java,role="primary"]
  1310. ----
  1311. @EnableMethodSecurity
  1312. ----
  1313. Kotlin::
  1314. +
  1315. [source,kotlin,role="secondary"]
  1316. ----
  1317. @EnableMethodSecurity
  1318. ----
  1319. Xml::
  1320. +
  1321. [source,xml,role="secondary"]
  1322. ----
  1323. <method-security/>
  1324. ----
  1325. ======
  1326. For applications not using the pre-post annotations, make sure to turn it off to avoid activating unwanted behavior.
  1327. For example, a listing like:
  1328. [tabs]
  1329. ======
  1330. Java::
  1331. +
  1332. [source,java,role="primary"]
  1333. ----
  1334. @EnableGlobalMethodSecurity(securedEnabled = true)
  1335. ----
  1336. Kotlin::
  1337. +
  1338. [source,kotlin,role="secondary"]
  1339. ----
  1340. @EnableGlobalMethodSecurity(securedEnabled = true)
  1341. ----
  1342. Xml::
  1343. +
  1344. [source,xml,role="secondary"]
  1345. ----
  1346. <global-method-security secured-enabled="true"/>
  1347. ----
  1348. ======
  1349. should change to:
  1350. [tabs]
  1351. ======
  1352. Java::
  1353. +
  1354. [source,java,role="primary"]
  1355. ----
  1356. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  1357. ----
  1358. Kotlin::
  1359. +
  1360. [source,kotlin,role="secondary"]
  1361. ----
  1362. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  1363. ----
  1364. Xml::
  1365. +
  1366. [source,xml,role="secondary"]
  1367. ----
  1368. <method-security secured-enabled="true" pre-post-enabled="false"/>
  1369. ----
  1370. ======
  1371. === Use a Custom `@Bean` instead of subclassing `DefaultMethodSecurityExpressionHandler`
  1372. As a performance optimization, a new method was introduced to `MethodSecurityExpressionHandler` that takes a `Supplier<Authentication>` instead of an `Authentication`.
  1373. This allows Spring Security to defer the lookup of the `Authentication`, and is taken advantage of automatically when you use `@EnableMethodSecurity` instead of `@EnableGlobalMethodSecurity`.
  1374. However, let's say that your code extends `DefaultMethodSecurityExpressionHandler` and overrides `createSecurityExpressionRoot(Authentication, MethodInvocation)` to return a custom `SecurityExpressionRoot` instance.
  1375. This will no longer work because the arrangement that `@EnableMethodSecurity` sets up calls `createEvaluationContext(Supplier<Authentication>, MethodInvocation)` instead.
  1376. Happily, such a level of customization is often unnecessary.
  1377. Instead, you can create a custom bean with the authorization methods that you need.
  1378. For example, let's say you are wanting a custom evaluation of `@PostAuthorize("hasAuthority('ADMIN')")`.
  1379. You can create a custom `@Bean` like this one:
  1380. [tabs]
  1381. ======
  1382. Java::
  1383. +
  1384. [source,java,role="primary"]
  1385. ----
  1386. class MyAuthorizer {
  1387. boolean isAdmin(MethodSecurityExpressionOperations root) {
  1388. boolean decision = root.hasAuthority("ADMIN");
  1389. // custom work ...
  1390. return decision;
  1391. }
  1392. }
  1393. ----
  1394. Kotlin::
  1395. +
  1396. [source,kotlin,role="secondary"]
  1397. ----
  1398. class MyAuthorizer {
  1399. fun isAdmin(val root: MethodSecurityExpressionOperations): boolean {
  1400. val decision = root.hasAuthority("ADMIN");
  1401. // custom work ...
  1402. return decision;
  1403. }
  1404. }
  1405. ----
  1406. ======
  1407. and then refer to it in the annotation like so:
  1408. [tabs]
  1409. ======
  1410. Java::
  1411. +
  1412. [source,java,role="primary"]
  1413. ----
  1414. @PreAuthorize("@authz.isAdmin(#root)")
  1415. ----
  1416. Kotlin::
  1417. +
  1418. [source,kotlin,role="secondary"]
  1419. ----
  1420. @PreAuthorize("@authz.isAdmin(#root)")
  1421. ----
  1422. ======
  1423. [[subclass-defaultmethodsecurityexpressionhandler]]
  1424. ==== I'd still prefer to subclass `DefaultMethodSecurityExpressionHandler`
  1425. If you must continue subclassing `DefaultMethodSecurityExpressionHandler`, you can still do so.
  1426. Instead, override the `createEvaluationContext(Supplier<Authentication>, MethodInvocation)` method like so:
  1427. [tabs]
  1428. ======
  1429. Java::
  1430. +
  1431. [source,java,role="primary"]
  1432. ----
  1433. @Component
  1434. class MyExpressionHandler extends DefaultMethodSecurityExpressionHandler {
  1435. @Override
  1436. public EvaluationContext createEvaluationContext(Supplier<Authentication> authentication, MethodInvocation mi) {
  1437. StandardEvaluationContext context = (StandardEvaluationContext) super.createEvaluationContext(authentication, mi);
  1438. MethodSecurityExpressionOperations delegate = (MethodSecurityExpressionOperations) context.getRootObject().getValue();
  1439. MySecurityExpressionRoot root = new MySecurityExpressionRoot(delegate);
  1440. context.setRootObject(root);
  1441. return context;
  1442. }
  1443. }
  1444. ----
  1445. Kotlin::
  1446. +
  1447. [source,kotlin,role="secondary"]
  1448. ----
  1449. @Component
  1450. class MyExpressionHandler: DefaultMethodSecurityExpressionHandler {
  1451. override fun createEvaluationContext(val authentication: Supplier<Authentication>,
  1452. val mi: MethodInvocation): EvaluationContext {
  1453. val context = super.createEvaluationContext(authentication, mi) as StandardEvaluationContext
  1454. val delegate = context.getRootObject().getValue() as MethodSecurityExpressionOperations
  1455. val root = MySecurityExpressionRoot(delegate)
  1456. context.setRootObject(root);
  1457. return context;
  1458. }
  1459. }
  1460. ----
  1461. ======
  1462. == Further Reading
  1463. Now that you have secured your application's requests, please xref:servlet/authorization/authorize-http-requests.adoc[secure its requests] if you haven't already.
  1464. You can also read further on xref:servlet/test/index.adoc[testing your application] or on integrating Spring Security with other aspects of you application like xref:servlet/integrations/data.adoc[the data layer] or xref:servlet/integrations/observability.adoc[tracing and metrics].