method-security.adoc 57 KB

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