method-security.adoc 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404
  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[`AuthorizationManagerBeforeMethodInterceptor#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[`AuthorizationManagerBeforeMethodInterceptor#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[`AuthorizationManagerBeforeMethodInterceptor#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[`AuthorizationManagerBeforeMethodInterceptor#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 RoleHierarchyImpl.fromHierarchy("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.fromHierarchy("ROLE_ADMIN > permission:read")
  199. }
  200. }
  201. ----
  202. Xml::
  203. +
  204. [source,xml,role="secondary"]
  205. ----
  206. <bean id="roleHierarchy"
  207. class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl" factory-method="fromHierarchy">
  208. <constructor-arg value="ROLE_ADMIN > permission:read"/>
  209. </bean>
  210. ----
  211. ======
  212. and then <<customizing-expression-handling,set that in a `MethodSecurityExpressionHandler` instance>>.
  213. This then allows you to have a simpler <<use-preauthorize,`@PreAuthorize`>> expression like this one:
  214. [tabs]
  215. ======
  216. Java::
  217. +
  218. [source,java,role="primary"]
  219. ----
  220. @PreAuthorize("hasAuthority('permission:read')")
  221. ----
  222. Kotlin::
  223. +
  224. [source,kotlin,role="secondary"]
  225. ----
  226. @PreAuthorize("hasAuthority('permission:read')")
  227. ----
  228. ======
  229. Or, where possible, adapt application-specific authorization logic into granted authorities at login time.
  230. [[request-vs-method]]
  231. == Comparing Request-level vs Method-level Authorization
  232. When should you favor method-level authorization over xref:servlet/authorization/authorize-http-requests.adoc[request-level authorization]?
  233. Some of it comes down to taste; however, consider the following strengths list of each to help you decide.
  234. |===
  235. || *request-level* | *method-level*
  236. | *authorization type* | coarse-grained | fine-grained
  237. | *configuration location* | declared in a config class | local to method declaration
  238. | *configuration style* | DSL | Annotations
  239. | *authorization definitions* | programmatic | SpEL
  240. |===
  241. The main tradeoff seems to be where you want your authorization rules to live.
  242. [NOTE]
  243. It's important to remember that when you use annotation-based Method Security, then unannotated methods are not secured.
  244. 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.
  245. [[authorizing-with-annotations]]
  246. == Authorizing with Annotations
  247. The primary way Spring Security enables method-level authorization support is through annotations that you can add to methods, classes, and interfaces.
  248. [[use-preauthorize]]
  249. === Authorizing Method Invocation with `@PreAuthorize`
  250. 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:
  251. [tabs]
  252. ======
  253. Java::
  254. +
  255. [source,java,role="primary"]
  256. ----
  257. @Component
  258. public class BankService {
  259. @PreAuthorize("hasRole('ADMIN')")
  260. public Account readAccount(Long id) {
  261. // ... is only invoked if the `Authentication` has the `ROLE_ADMIN` authority
  262. }
  263. }
  264. ----
  265. Kotlin::
  266. +
  267. [source,kotlin,role="secondary"]
  268. ----
  269. @Component
  270. open class BankService {
  271. @PreAuthorize("hasRole('ADMIN')")
  272. fun readAccount(val id: Long): Account {
  273. // ... is only invoked if the `Authentication` has the `ROLE_ADMIN` authority
  274. }
  275. }
  276. ----
  277. ======
  278. This is meant to indicate that the method can only be invoked if the provided expression `hasRole('ADMIN')` passes.
  279. You can then xref:servlet/test/method.adoc[test the class] to confirm it is enforcing the authorization rule like so:
  280. [tabs]
  281. ======
  282. Java::
  283. +
  284. [source,java,role="primary"]
  285. ----
  286. @Autowired
  287. BankService bankService;
  288. @WithMockUser(roles="ADMIN")
  289. @Test
  290. void readAccountWithAdminRoleThenInvokes() {
  291. Account account = this.bankService.readAccount("12345678");
  292. // ... assertions
  293. }
  294. @WithMockUser(roles="WRONG")
  295. @Test
  296. void readAccountWithWrongRoleThenAccessDenied() {
  297. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(
  298. () -> this.bankService.readAccount("12345678"));
  299. }
  300. ----
  301. Kotlin::
  302. +
  303. [source,kotlin,role="secondary"]
  304. ----
  305. @WithMockUser(roles="ADMIN")
  306. @Test
  307. fun readAccountWithAdminRoleThenInvokes() {
  308. val account: Account = this.bankService.readAccount("12345678")
  309. // ... assertions
  310. }
  311. @WithMockUser(roles="WRONG")
  312. @Test
  313. fun readAccountWithWrongRoleThenAccessDenied() {
  314. assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy {
  315. this.bankService.readAccount("12345678")
  316. }
  317. }
  318. ----
  319. ======
  320. [TIP]
  321. `@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>>.
  322. 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>>.
  323. [[use-postauthorize]]
  324. === Authorization Method Results with `@PostAuthorize`
  325. 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:
  326. [tabs]
  327. ======
  328. Java::
  329. +
  330. [source,java,role="primary"]
  331. ----
  332. @Component
  333. public class BankService {
  334. @PostAuthorize("returnObject.owner == authentication.name")
  335. public Account readAccount(Long id) {
  336. // ... is only returned if the `Account` belongs to the logged in user
  337. }
  338. }
  339. ----
  340. Kotlin::
  341. +
  342. [source,kotlin,role="secondary"]
  343. ----
  344. @Component
  345. open class BankService {
  346. @PostAuthorize("returnObject.owner == authentication.name")
  347. fun readAccount(val id: Long): Account {
  348. // ... is only returned if the `Account` belongs to the logged in user
  349. }
  350. }
  351. ----
  352. ======
  353. This is meant to indicate that the method can only return the value if the provided expression `returnObject.owner == authentication.name` passes.
  354. `returnObject` represents the `Account` object to be returned.
  355. You can then xref:servlet/test/method.adoc[test the class] to confirm it is enforcing the authorization rule:
  356. [tabs]
  357. ======
  358. Java::
  359. +
  360. [source,java,role="primary"]
  361. ----
  362. @Autowired
  363. BankService bankService;
  364. @WithMockUser(username="owner")
  365. @Test
  366. void readAccountWhenOwnedThenReturns() {
  367. Account account = this.bankService.readAccount("12345678");
  368. // ... assertions
  369. }
  370. @WithMockUser(username="wrong")
  371. @Test
  372. void readAccountWhenNotOwnedThenAccessDenied() {
  373. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(
  374. () -> this.bankService.readAccount("12345678"));
  375. }
  376. ----
  377. Kotlin::
  378. +
  379. [source,kotlin,role="secondary"]
  380. ----
  381. @WithMockUser(username="owner")
  382. @Test
  383. fun readAccountWhenOwnedThenReturns() {
  384. val account: Account = this.bankService.readAccount("12345678")
  385. // ... assertions
  386. }
  387. @WithMockUser(username="wrong")
  388. @Test
  389. fun readAccountWhenNotOwnedThenAccessDenied() {
  390. assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy {
  391. this.bankService.readAccount("12345678")
  392. }
  393. }
  394. ----
  395. ======
  396. [TIP]
  397. `@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>>.
  398. `@PostAuthorize` is particularly helpful when defending against https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html[Insecure Direct Object Reference].
  399. In fact, it can be defined as a <<meta-annotations,meta-annotation>> like so:
  400. [tabs]
  401. ======
  402. Java::
  403. +
  404. [source,java,role="primary"]
  405. ----
  406. @Target({ ElementType.METHOD, ElementType.TYPE })
  407. @Retention(RetentionPolicy.RUNTIME)
  408. @PostAuthorize("returnObject.owner == authentication.name")
  409. public @interface RequireOwnership {}
  410. ----
  411. Kotlin::
  412. +
  413. [source,kotlin,role="secondary"]
  414. ----
  415. @Target(ElementType.METHOD, ElementType.TYPE)
  416. @Retention(RetentionPolicy.RUNTIME)
  417. @PostAuthorize("returnObject.owner == authentication.name")
  418. annotation class RequireOwnership
  419. ----
  420. ======
  421. Allowing you to instead annotate the service in the following way:
  422. [tabs]
  423. ======
  424. Java::
  425. +
  426. [source,java,role="primary"]
  427. ----
  428. @Component
  429. public class BankService {
  430. @RequireOwnership
  431. public Account readAccount(Long id) {
  432. // ... is only returned if the `Account` belongs to the logged in user
  433. }
  434. }
  435. ----
  436. Kotlin::
  437. +
  438. [source,kotlin,role="secondary"]
  439. ----
  440. @Component
  441. open class BankService {
  442. @RequireOwnership
  443. fun readAccount(val id: Long): Account {
  444. // ... is only returned if the `Account` belongs to the logged in user
  445. }
  446. }
  447. ----
  448. ======
  449. The result is that the above method will only return the `Account` if its `owner` attribute matches the logged-in user's `name`.
  450. If not, Spring Security will throw an `AccessDeniedException` and return a 403 status code.
  451. [[use-prefilter]]
  452. === Filtering Method Parameters with `@PreFilter`
  453. [NOTE]
  454. `@PreFilter` is not yet supported for Kotlin-specific data types; for that reason, only Java snippets are shown
  455. 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:
  456. [tabs]
  457. ======
  458. Java::
  459. +
  460. [source,java,role="primary"]
  461. ----
  462. @Component
  463. public class BankService {
  464. @PreFilter("filterObject.owner == authentication.name")
  465. public Collection<Account> updateAccounts(Account... accounts) {
  466. // ... `accounts` will only contain the accounts owned by the logged-in user
  467. return updated;
  468. }
  469. }
  470. ----
  471. ======
  472. This is meant to filter out any values from `accounts` where the expression `filterObject.owner == authentication.name` fails.
  473. `filterObject` represents each `account` in `accounts` and is used to test each `account`.
  474. You can then test the class in the following way to confirm it is enforcing the authorization rule:
  475. [tabs]
  476. ======
  477. Java::
  478. +
  479. [source,java,role="primary"]
  480. ----
  481. @Autowired
  482. BankService bankService;
  483. @WithMockUser(username="owner")
  484. @Test
  485. void updateAccountsWhenOwnedThenReturns() {
  486. Account ownedBy = ...
  487. Account notOwnedBy = ...
  488. Collection<Account> updated = this.bankService.updateAccounts(ownedBy, notOwnedBy);
  489. assertThat(updated).containsOnly(ownedBy);
  490. }
  491. ----
  492. ======
  493. [TIP]
  494. `@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>>.
  495. `@PreFilter` supports arrays, collections, maps, and streams (so long as the stream is still open).
  496. For example, the above `updateAccounts` declaration will function the same way as the following other four:
  497. [tabs]
  498. ======
  499. Java::
  500. +
  501. [source,java,role="primary"]
  502. ----
  503. @PreFilter("filterObject.owner == authentication.name")
  504. public Collection<Account> updateAccounts(Account[] accounts)
  505. @PreFilter("filterObject.owner == authentication.name")
  506. public Collection<Account> updateAccounts(Collection<Account> accounts)
  507. @PreFilter("filterObject.value.owner == authentication.name")
  508. public Collection<Account> updateAccounts(Map<String, Account> accounts)
  509. @PreFilter("filterObject.owner == authentication.name")
  510. public Collection<Account> updateAccounts(Stream<Account> accounts)
  511. ----
  512. ======
  513. The result is that the above method will only have the `Account` instances where their `owner` attribute matches the logged-in user's `name`.
  514. [[use-postfilter]]
  515. === Filtering Method Results with `@PostFilter`
  516. [NOTE]
  517. `@PostFilter` is not yet supported for Kotlin-specific data types; for that reason, only Java snippets are shown
  518. 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:
  519. [tabs]
  520. ======
  521. Java::
  522. +
  523. [source,java,role="primary"]
  524. ----
  525. @Component
  526. public class BankService {
  527. @PostFilter("filterObject.owner == authentication.name")
  528. public Collection<Account> readAccounts(String... ids) {
  529. // ... the return value will be filtered to only contain the accounts owned by the logged-in user
  530. return accounts;
  531. }
  532. }
  533. ----
  534. ======
  535. This is meant to filter out any values from the return value where the expression `filterObject.owner == authentication.name` fails.
  536. `filterObject` represents each `account` in `accounts` and is used to test each `account`.
  537. You can then test the class like so to confirm it is enforcing the authorization rule:
  538. [tabs]
  539. ======
  540. Java::
  541. +
  542. [source,java,role="primary"]
  543. ----
  544. @Autowired
  545. BankService bankService;
  546. @WithMockUser(username="owner")
  547. @Test
  548. void readAccountsWhenOwnedThenReturns() {
  549. Collection<Account> accounts = this.bankService.updateAccounts("owner", "not-owner");
  550. assertThat(accounts).hasSize(1);
  551. assertThat(accounts.get(0).getOwner()).isEqualTo("owner");
  552. }
  553. ----
  554. ======
  555. [TIP]
  556. `@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>>.
  557. `@PostFilter` supports arrays, collections, maps, and streams (so long as the stream is still open).
  558. For example, the above `readAccounts` declaration will function the same way as the following other three:
  559. ```java
  560. @PostFilter("filterObject.owner == authentication.name")
  561. public Account[] readAccounts(String... ids)
  562. @PostFilter("filterObject.value.owner == authentication.name")
  563. public Map<String, Account> readAccounts(String... ids)
  564. @PostFilter("filterObject.owner == authentication.name")
  565. public Stream<Account> readAccounts(String... ids)
  566. ```
  567. The result is that the above method will return the `Account` instances where their `owner` attribute matches the logged-in user's `name`.
  568. [NOTE]
  569. 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.
  570. [[use-secured]]
  571. === Authorizing Method Invocation with `@Secured`
  572. {security-api-url}org/springframework/security/access/annotation/Secured.html[`@Secured`] is a legacy option for authorizing invocations.
  573. <<use-preauthorize,`@PreAuthorize`>> supercedes it and is recommended instead.
  574. To use the `@Secured` annotation, you should first change your Method Security declaration to enable it like so:
  575. [tabs]
  576. ======
  577. Java::
  578. +
  579. [source,java,role="primary"]
  580. ----
  581. @EnableMethodSecurity(securedEnabled = true)
  582. ----
  583. Kotlin::
  584. +
  585. [source,kotlin,role="secondary"]
  586. ----
  587. @EnableMethodSecurity(securedEnabled = true)
  588. ----
  589. Xml::
  590. +
  591. [source,xml,role="secondary"]
  592. ----
  593. <sec:method-security secured-enabled="true"/>
  594. ----
  595. ======
  596. This will cause Spring Security to publish <<annotation-method-interceptors,the corresponding method interceptor>> that authorizes methods, classes, and interfaces annotated with `@Secured`.
  597. [[use-jsr250]]
  598. === Authorizing Method Invocation with JSR-250 Annotations
  599. In case you would like to use https://jcp.org/en/jsr/detail?id=250[JSR-250] annotations, Spring Security also supports that.
  600. <<use-preauthorize,`@PreAuthorize`>> has more expressive power and is thus recommended.
  601. To use the JSR-250 annotations, you should first change your Method Security declaration to enable them like so:
  602. [tabs]
  603. ======
  604. Java::
  605. +
  606. [source,java,role="primary"]
  607. ----
  608. @EnableMethodSecurity(jsr250Enabled = true)
  609. ----
  610. Kotlin::
  611. +
  612. [source,kotlin,role="secondary"]
  613. ----
  614. @EnableMethodSecurity(jsr250Enabled = true)
  615. ----
  616. Xml::
  617. +
  618. [source,xml,role="secondary"]
  619. ----
  620. <sec:method-security jsr250-enabled="true"/>
  621. ----
  622. ======
  623. 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`.
  624. [[class-or-interface-annotations]]
  625. === Declaring Annotations at the Class or Interface Level
  626. It's also supported to have Method Security annotations at the class and interface level.
  627. If it is at the class level like so:
  628. [tabs]
  629. ======
  630. Java::
  631. +
  632. [source,java,role="primary"]
  633. ----
  634. @Controller
  635. @PreAuthorize("hasAuthority('ROLE_USER')")
  636. public class MyController {
  637. @GetMapping("/endpoint")
  638. public String endpoint() { ... }
  639. }
  640. ----
  641. Kotlin::
  642. +
  643. [source,kotlin,role="secondary"]
  644. ----
  645. @Controller
  646. @PreAuthorize("hasAuthority('ROLE_USER')")
  647. open class MyController {
  648. @GetMapping("/endpoint")
  649. fun endpoint(): String { ... }
  650. }
  651. ----
  652. ======
  653. then all methods inherit the class-level behavior.
  654. Or, if it's declared like the following at both the class and method level:
  655. [tabs]
  656. ======
  657. Java::
  658. +
  659. [source,java,role="primary"]
  660. ----
  661. @Controller
  662. @PreAuthorize("hasAuthority('ROLE_USER')")
  663. public class MyController {
  664. @GetMapping("/endpoint")
  665. @PreAuthorize("hasAuthority('ROLE_ADMIN')")
  666. public String endpoint() { ... }
  667. }
  668. ----
  669. Kotlin::
  670. +
  671. [source,kotlin,role="secondary"]
  672. ----
  673. @Controller
  674. @PreAuthorize("hasAuthority('ROLE_USER')")
  675. open class MyController {
  676. @GetMapping("/endpoint")
  677. @PreAuthorize("hasAuthority('ROLE_ADMIN')")
  678. fun endpoint(): String { ... }
  679. }
  680. ----
  681. ======
  682. then methods declaring the annotation override the class-level annotation.
  683. The same is true for interfaces, with the exception that if a class inherits the annotation from two different interfaces, then startup will fail.
  684. This is because Spring Security has no way to tell which one you want to use.
  685. In cases like this, you can resolve the ambiguity by adding the annotation to the concrete method.
  686. [[meta-annotations]]
  687. === Using Meta Annotations
  688. Method Security supports meta annotations.
  689. This means that you can take any annotation and improve readability based on your application-specific use cases.
  690. For example, you can simplify `@PreAuthorize("hasRole('ADMIN')")` to `@IsAdmin` like so:
  691. [tabs]
  692. ======
  693. Java::
  694. +
  695. [source,java,role="primary"]
  696. ----
  697. @Target({ ElementType.METHOD, ElementType.TYPE })
  698. @Retention(RetentionPolicy.RUNTIME)
  699. @PreAuthorize("hasRole('ADMIN')")
  700. public @interface IsAdmin {}
  701. ----
  702. Kotlin::
  703. +
  704. [source,kotlin,role="secondary"]
  705. ----
  706. @Target(ElementType.METHOD, ElementType.TYPE)
  707. @Retention(RetentionPolicy.RUNTIME)
  708. @PreAuthorize("hasRole('ADMIN')")
  709. annotation class IsAdmin
  710. ----
  711. ======
  712. And the result is that on your secured methods you can now do the following instead:
  713. [tabs]
  714. ======
  715. Java::
  716. +
  717. [source,java,role="primary"]
  718. ----
  719. @Component
  720. public class BankService {
  721. @IsAdmin
  722. public Account readAccount(Long id) {
  723. // ... is only returned if the `Account` belongs to the logged in user
  724. }
  725. }
  726. ----
  727. Kotlin::
  728. +
  729. [source,kotlin,role="secondary"]
  730. ----
  731. @Component
  732. open class BankService {
  733. @IsAdmin
  734. fun readAccount(val id: Long): Account {
  735. // ... is only returned if the `Account` belongs to the logged in user
  736. }
  737. }
  738. ----
  739. ======
  740. This results in more readable method definitions.
  741. ==== Templating Meta-Annotation Expressions
  742. You can also opt into using meta-annotation templates, which allow for much more powerful annotation definitions.
  743. First, publish the following bean:
  744. [tabs]
  745. ======
  746. Java::
  747. +
  748. [source,java,role="primary"]
  749. ----
  750. @Bean
  751. static PrePostTemplateDefaults prePostTemplateDefaults() {
  752. return new PrePostTemplateDefaults();
  753. }
  754. ----
  755. Kotlin::
  756. +
  757. [source,kotlin,role="secondary"]
  758. ----
  759. companion object {
  760. @Bean
  761. fun prePostTemplateDefaults(): PrePostTemplateDefaults {
  762. return PrePostTemplateDefaults()
  763. }
  764. }
  765. ----
  766. ======
  767. Now instead of `@IsAdmin`, you can create something more powerful like `@HasRole` like so:
  768. [tabs]
  769. ======
  770. Java::
  771. +
  772. [source,java,role="primary"]
  773. ----
  774. @Target({ ElementType.METHOD, ElementType.TYPE })
  775. @Retention(RetentionPolicy.RUNTIME)
  776. @PreAuthorize("hasRole('{value}')")
  777. public @interface HasRole {
  778. String value();
  779. }
  780. ----
  781. Kotlin::
  782. +
  783. [source,kotlin,role="secondary"]
  784. ----
  785. @Target(ElementType.METHOD, ElementType.TYPE)
  786. @Retention(RetentionPolicy.RUNTIME)
  787. @PreAuthorize("hasRole('{value}')")
  788. annotation class IsAdmin(val value: String)
  789. ----
  790. ======
  791. And the result is that on your secured methods you can now do the following instead:
  792. [tabs]
  793. ======
  794. Java::
  795. +
  796. [source,java,role="primary"]
  797. ----
  798. @Component
  799. public class BankService {
  800. @HasRole("ADMIN")
  801. public Account readAccount(Long id) {
  802. // ... is only returned if the `Account` belongs to the logged in user
  803. }
  804. }
  805. ----
  806. Kotlin::
  807. +
  808. [source,kotlin,role="secondary"]
  809. ----
  810. @Component
  811. open class BankService {
  812. @HasRole("ADMIN")
  813. fun readAccount(val id: Long): Account {
  814. // ... is only returned if the `Account` belongs to the logged in user
  815. }
  816. }
  817. ----
  818. ======
  819. Note that this works with method variables and all annotation types, too, though you will want to be careful to correctly take care of quotation marks so the resulting SpEL expression is correct.
  820. For example, consider the following `@HasAnyRole` annotation:
  821. [tabs]
  822. ======
  823. Java::
  824. +
  825. [source,java,role="primary"]
  826. ----
  827. @Target({ ElementType.METHOD, ElementType.TYPE })
  828. @Retention(RetentionPolicy.RUNTIME)
  829. @PreAuthorize("hasAnyRole({roles})")
  830. public @interface HasAnyRole {
  831. String[] roles();
  832. }
  833. ----
  834. Kotlin::
  835. +
  836. [source,kotlin,role="secondary"]
  837. ----
  838. @Target(ElementType.METHOD, ElementType.TYPE)
  839. @Retention(RetentionPolicy.RUNTIME)
  840. @PreAuthorize("hasAnyRole({roles})")
  841. annotation class HasAnyRole(val roles: Array<String>)
  842. ----
  843. ======
  844. In that case, you'll notice that you should not use the quotation marks in the expression, but instead in the parameter value like so:
  845. [tabs]
  846. ======
  847. Java::
  848. +
  849. [source,java,role="primary"]
  850. ----
  851. @Component
  852. public class BankService {
  853. @HasAnyRole(roles = { "'USER'", "'ADMIN'" })
  854. public Account readAccount(Long id) {
  855. // ... is only returned if the `Account` belongs to the logged in user
  856. }
  857. }
  858. ----
  859. Kotlin::
  860. +
  861. [source,kotlin,role="secondary"]
  862. ----
  863. @Component
  864. open class BankService {
  865. @HasAnyRole(roles = arrayOf("'USER'", "'ADMIN'"))
  866. fun readAccount(val id: Long): Account {
  867. // ... is only returned if the `Account` belongs to the logged in user
  868. }
  869. }
  870. ----
  871. ======
  872. so that, once replaced, the expression becomes `@PreAuthorize("hasAnyRole('USER', 'ADMIN')")`.
  873. [[enable-annotation]]
  874. === Enabling Certain Annotations
  875. You can turn off ``@EnableMethodSecurity``'s pre-configuration and replace it with you own.
  876. You may choose to do this if you want to <<custom-authorization-managers,customize the `AuthorizationManager`>> or `Pointcut`.
  877. Or you may simply want to only enable a specific annotation, like `@PostAuthorize`.
  878. You can do this in the following way:
  879. .Only @PostAuthorize Configuration
  880. [tabs]
  881. ======
  882. Java::
  883. +
  884. [source,java,role="primary"]
  885. ----
  886. @Configuration
  887. @EnableMethodSecurity(prePostEnabled = false)
  888. class MethodSecurityConfig {
  889. @Bean
  890. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  891. Advisor postAuthorize() {
  892. return AuthorizationManagerBeforeMethodInterceptor.postAuthorize();
  893. }
  894. }
  895. ----
  896. Kotlin::
  897. +
  898. [source,kotlin,role="secondary"]
  899. ----
  900. @Configuration
  901. @EnableMethodSecurity(prePostEnabled = false)
  902. class MethodSecurityConfig {
  903. @Bean
  904. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  905. fun postAuthorize() : Advisor {
  906. return AuthorizationManagerBeforeMethodInterceptor.postAuthorize()
  907. }
  908. }
  909. ----
  910. Xml::
  911. +
  912. [source,xml,role="secondary"]
  913. ----
  914. <sec:method-security pre-post-enabled="false"/>
  915. <aop:config/>
  916. <bean id="postAuthorize"
  917. class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor"
  918. factory-method="postAuthorize"/>
  919. ----
  920. ======
  921. The above snippet achieves this by first disabling Method Security's pre-configurations and then publishing <<annotation-method-interceptors, the `@PostAuthorize` interceptor>> itself.
  922. [[use-intercept-methods]]
  923. == Authorizing with `<intercept-methods>`
  924. 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.
  925. 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:
  926. [tabs]
  927. ======
  928. Xml::
  929. +
  930. [source,xml,role="primary"]
  931. ----
  932. <bean class="org.mycompany.MyController">
  933. <intercept-methods>
  934. <protect method="get*" access="hasAuthority('read')"/>
  935. <protect method="*" access="hasAuthority('write')"/>
  936. </intercept-methods>
  937. </bean>
  938. ----
  939. ======
  940. [NOTE]
  941. This only supports matching method by prefix or by name.
  942. If your needs are more complex than that, <<authorizing-with-annotations,use annotation support>> instead.
  943. [[use-programmatic-authorization]]
  944. == Authorizing Methods Programmatically
  945. As you've already seen, there are several ways that you can specify non-trivial authorization rules using <<authorization-expressions, Method Security SpEL expressions>>.
  946. There are a number of ways that you can instead allow your logic to be Java-based instead of SpEL-based.
  947. This gives use access the entire Java language for increased testability and flow control.
  948. === Using a Custom Bean in SpEL
  949. The first way to authorize a method programmatically is a two-step process.
  950. First, declare a bean that has a method that takes a `MethodSecurityExpressionOperations` instance like the following:
  951. [tabs]
  952. ======
  953. Java::
  954. +
  955. [source,java,role="primary"]
  956. ----
  957. @Component("authz")
  958. public class AuthorizationLogic {
  959. public boolean decide(MethodSecurityExpressionOperations operations) {
  960. // ... authorization logic
  961. }
  962. }
  963. ----
  964. Kotlin::
  965. +
  966. [source,kotlin,role="secondary"]
  967. ----
  968. @Component("authz")
  969. open class AuthorizationLogic {
  970. fun decide(val operations: MethodSecurityExpressionOperations): boolean {
  971. // ... authorization logic
  972. }
  973. }
  974. ----
  975. ======
  976. Then, reference that bean in your annotations in the following way:
  977. [tabs]
  978. ======
  979. Java::
  980. +
  981. [source,java,role="primary"]
  982. ----
  983. @Controller
  984. public class MyController {
  985. @PreAuthorize("@authz.decide(#root)")
  986. @GetMapping("/endpoint")
  987. public String endpoint() {
  988. // ...
  989. }
  990. }
  991. ----
  992. Kotlin::
  993. +
  994. [source,kotlin,role="secondary"]
  995. ----
  996. @Controller
  997. open class MyController {
  998. @PreAuthorize("@authz.decide(#root)")
  999. @GetMapping("/endpoint")
  1000. fun String endpoint() {
  1001. // ...
  1002. }
  1003. }
  1004. ----
  1005. ======
  1006. Spring Security will invoke the given method on that bean for each method invocation.
  1007. 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.
  1008. It also has access to the full Java language.
  1009. [[custom-authorization-managers]]
  1010. === Using a Custom Authorization Manager
  1011. The second way to authorize a method programmatically is to create a custom xref:servlet/authorization/architecture.adoc#_the_authorizationmanager[`AuthorizationManager`].
  1012. First, declare an authorization manager instance, perhaps like this one:
  1013. [tabs]
  1014. ======
  1015. Java::
  1016. +
  1017. [source,java,role="primary"]
  1018. ----
  1019. @Component
  1020. public class MyAuthorizationManager implements AuthorizationManager<MethodInvocation>, AuthorizationManager<MethodInvocationResult> {
  1021. @Override
  1022. public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocation invocation) {
  1023. // ... authorization logic
  1024. }
  1025. @Override
  1026. public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocationResult invocation) {
  1027. // ... authorization logic
  1028. }
  1029. }
  1030. ----
  1031. Kotlin::
  1032. +
  1033. [source,kotlin,role="secondary"]
  1034. ----
  1035. @Component
  1036. class MyAuthorizationManager : AuthorizationManager<MethodInvocation>, AuthorizationManager<MethodInvocationResult> {
  1037. override fun check(authentication: Supplier<Authentication>, invocation: MethodInvocation): AuthorizationDecision {
  1038. // ... authorization logic
  1039. }
  1040. override fun check(authentication: Supplier<Authentication>, invocation: MethodInvocationResult): AuthorizationDecision {
  1041. // ... authorization logic
  1042. }
  1043. }
  1044. ----
  1045. ======
  1046. Then, publish the method interceptor with a pointcut that corresponds to when you want that `AuthorizationManager` to run.
  1047. For example, you could replace how `@PreAuthorize` and `@PostAuthorize` work like so:
  1048. .Only @PreAuthorize and @PostAuthorize Configuration
  1049. [tabs]
  1050. ======
  1051. Java::
  1052. +
  1053. [source,java,role="primary"]
  1054. ----
  1055. @Configuration
  1056. @EnableMethodSecurity(prePostEnabled = false)
  1057. class MethodSecurityConfig {
  1058. @Bean
  1059. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1060. Advisor preAuthorize(MyAuthorizationManager manager) {
  1061. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(manager);
  1062. }
  1063. @Bean
  1064. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1065. Advisor postAuthorize(MyAuthorizationManager manager) {
  1066. return AuthorizationManagerAfterMethodInterceptor.postAuthorize(manager);
  1067. }
  1068. }
  1069. ----
  1070. Kotlin::
  1071. +
  1072. [source,kotlin,role="secondary"]
  1073. ----
  1074. @Configuration
  1075. @EnableMethodSecurity(prePostEnabled = false)
  1076. class MethodSecurityConfig {
  1077. @Bean
  1078. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1079. fun preAuthorize(val manager: MyAuthorizationManager) : Advisor {
  1080. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(manager)
  1081. }
  1082. @Bean
  1083. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1084. fun postAuthorize(val manager: MyAuthorizationManager) : Advisor {
  1085. return AuthorizationManagerAfterMethodInterceptor.postAuthorize(manager)
  1086. }
  1087. }
  1088. ----
  1089. Xml::
  1090. +
  1091. [source,xml,role="secondary"]
  1092. ----
  1093. <sec:method-security pre-post-enabled="false"/>
  1094. <aop:config/>
  1095. <bean id="preAuthorize"
  1096. class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor"
  1097. factory-method="preAuthorize">
  1098. <constructor-arg ref="myAuthorizationManager"/>
  1099. </bean>
  1100. <bean id="postAuthorize"
  1101. class="org.springframework.security.authorization.method.AuthorizationManagerAfterMethodInterceptor"
  1102. factory-method="postAuthorize">
  1103. <constructor-arg ref="myAuthorizationManager"/>
  1104. </bean>
  1105. ----
  1106. ======
  1107. [TIP]
  1108. ====
  1109. You can place your interceptor in between Spring Security method interceptors using the order constants specified in `AuthorizationInterceptorsOrder`.
  1110. ====
  1111. [[customizing-expression-handling]]
  1112. === Customizing Expression Handling
  1113. Or, third, you can customize how each SpEL expression is handled.
  1114. To do that, you can expose a custom {security-api-url}org.springframework.security.access.expression.method.MethodSecurityExpressionHandler.html[`MethodSecurityExpressionHandler`], like so:
  1115. .Custom MethodSecurityExpressionHandler
  1116. [tabs]
  1117. ======
  1118. Java::
  1119. +
  1120. [source,java,role="primary"]
  1121. ----
  1122. @Bean
  1123. static MethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) {
  1124. DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
  1125. handler.setRoleHierarchy(roleHierarchy);
  1126. return handler;
  1127. }
  1128. ----
  1129. Kotlin::
  1130. +
  1131. [source,kotlin,role="secondary"]
  1132. ----
  1133. companion object {
  1134. @Bean
  1135. fun methodSecurityExpressionHandler(val roleHierarchy: RoleHierarchy) : MethodSecurityExpressionHandler {
  1136. val handler = DefaultMethodSecurityExpressionHandler()
  1137. handler.setRoleHierarchy(roleHierarchy)
  1138. return handler
  1139. }
  1140. }
  1141. ----
  1142. Xml::
  1143. +
  1144. [source,xml,role="secondary"]
  1145. ----
  1146. <sec:method-security>
  1147. <sec:expression-handler ref="myExpressionHandler"/>
  1148. </sec:method-security>
  1149. <bean id="myExpressionHandler"
  1150. class="org.springframework.security.messaging.access.expression.DefaultMessageSecurityExpressionHandler">
  1151. <property name="roleHierarchy" ref="roleHierarchy"/>
  1152. </bean>
  1153. ----
  1154. ======
  1155. [TIP]
  1156. ====
  1157. We expose `MethodSecurityExpressionHandler` using a `static` method to ensure that Spring publishes it before it initializes Spring Security's method security `@Configuration` classes
  1158. ====
  1159. You can also <<subclass-defaultmethodsecurityexpressionhandler,subclass `DefaultMessageSecurityExpressionHandler`>> to add your own custom authorization expressions beyond the defaults.
  1160. [[use-aspectj]]
  1161. == Authorizing with AspectJ
  1162. [[match-by-pointcut]]
  1163. === Matching Methods with Custom Pointcuts
  1164. 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].
  1165. This has the potential advantage of centralizing method-level authorization rules.
  1166. 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:
  1167. [tabs]
  1168. ======
  1169. Java::
  1170. +
  1171. [source,java,role="primary"]
  1172. ----
  1173. import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole
  1174. @Bean
  1175. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1176. static Advisor protectServicePointcut() {
  1177. AspectJExpressionPointcut pattern = new AspectJExpressionPointcut()
  1178. pattern.setExpression("execution(* com.mycompany.*Service.*(..))")
  1179. return new AuthorizationManagerBeforeMethodInterceptor(pattern, hasRole("USER"))
  1180. }
  1181. ----
  1182. Kotlin::
  1183. +
  1184. [source,kotlin,role="secondary"]
  1185. ----
  1186. import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole
  1187. companion object {
  1188. @Bean
  1189. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1190. fun protectServicePointcut(): Advisor {
  1191. val pattern = AspectJExpressionPointcut()
  1192. pattern.setExpression("execution(* com.mycompany.*Service.*(..))")
  1193. return new AuthorizationManagerBeforeMethodInterceptor(pattern, hasRole("USER"))
  1194. }
  1195. }
  1196. ----
  1197. Xml::
  1198. +
  1199. [source,xml,role="secondary"]
  1200. ----
  1201. <sec:method-security>
  1202. <protect-pointcut expression="execution(* com.mycompany.*Service.*(..))" access="hasRole('USER')"/>
  1203. </sec:method-security>
  1204. ----
  1205. ======
  1206. [[weave-aspectj]]
  1207. === Integrate with AspectJ Byte-weaving
  1208. Performance can at times be enhanced by using AspectJ to weave Spring Security advice into the byte code of your beans.
  1209. After setting up AspectJ, you can quite simply state in the `@EnableMethodSecurity` annotation or `<method-security>` element that you are using AspectJ:
  1210. [tabs]
  1211. ======
  1212. Java::
  1213. +
  1214. [source,java,role="primary"]
  1215. ----
  1216. @EnableMethodSecurity(mode=AdviceMode.ASPECTJ)
  1217. ----
  1218. Kotlin::
  1219. +
  1220. [source,kotlin,role="secondary"]
  1221. ----
  1222. @EnableMethodSecurity(mode=AdviceMode.ASPECTJ)
  1223. ----
  1224. Xml::
  1225. +
  1226. [source,xml,role="secondary"]
  1227. ----
  1228. <sec:method-security mode="aspectj"/>
  1229. ----
  1230. ======
  1231. And the result will be that Spring Security will publish its advisors as AspectJ advice so that they can be woven in accordingly.
  1232. [[changing-the-order]]
  1233. == Specifying Order
  1234. 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.
  1235. Namely, the `@PreFilter` method interceptor's order is 100, ``@PreAuthorize``'s is 200, and so on.
  1236. 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`.
  1237. In other words, they are located at the end of the advisor chain by default.
  1238. At times, it can be valuable to have other advice execute before Spring Security.
  1239. 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.
  1240. To get `@EnableTransactionManagement` to open a transaction before method authorization advice runs, you can set ``@EnableTransactionManagement``'s order like so:
  1241. [tabs]
  1242. ======
  1243. Java::
  1244. +
  1245. [source,java,role="primary"]
  1246. ----
  1247. @EnableTransactionManagement(order = 0)
  1248. ----
  1249. Kotlin::
  1250. +
  1251. [source,kotlin,role="secondary"]
  1252. ----
  1253. @EnableTransactionManagement(order = 0)
  1254. ----
  1255. Xml::
  1256. +
  1257. [source,xml,role="secondary"]
  1258. ----
  1259. <tx:annotation-driven ref="txManager" order="0"/>
  1260. ----
  1261. ======
  1262. 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.
  1263. [[authorization-expressions]]
  1264. == Expressing Authorization with SpEL
  1265. You've already seen several examples using SpEL, so now let's cover the API a bit more in depth.
  1266. Spring Security encapsulates all of its authorization fields and methods in a set of root objects.
  1267. The most generic root object is called `SecurityExpressionRoot` and it forms the basis for `MethodSecurityExpressionRoot`.
  1268. Spring Security supplies this root object to `MethodSecurityEvaluationContext` when preparing to evaluate an authorization expression.
  1269. [[using-authorization-expression-fields-and-methods]]
  1270. === Using Authorization Expression Fields and Methods
  1271. The first thing this provides is an enhanced set of authorization fields and methods to your SpEL expressions.
  1272. What follows is a quick overview of the most common methods:
  1273. * `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
  1274. * `denyAll` - The method is not allowed under any circumstances; note that in this case, the `Authentication` is never retrieved from the session
  1275. * `hasAuthority` - The method requires that the `Authentication` have xref:servlet/authorization/architecture.adoc#authz-authorities[a `GrantedAuthority`] that matches the given value
  1276. * `hasRole` - A shortcut for `hasAuthority` that prefixes `ROLE_` or whatever is configured as the default prefix
  1277. * `hasAnyAuthority` - The method requires that the `Authentication` have a `GrantedAuthority` that matches any of the given values
  1278. * `hasAnyRole` - A shortcut for `hasAnyAuthority` that prefixes `ROLE_` or whatever is configured as the default prefix
  1279. * `hasPermission` - A hook into your `PermissionEvaluator` instance for doing object-level authorization
  1280. And here is a brief look at the most common fields:
  1281. * `authentication` - The `Authentication` instance associated with this method invocation
  1282. * `principal` - The `Authentication#getPrincipal` associated with this method invocation
  1283. 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:
  1284. .Authorize Requests
  1285. [tabs]
  1286. ======
  1287. Java::
  1288. +
  1289. [source,java,role="primary"]
  1290. ----
  1291. @Component
  1292. public class MyService {
  1293. @PreAuthorize("denyAll") <1>
  1294. MyResource myDeprecatedMethod(...);
  1295. @PreAuthorize("hasRole('ADMIN')") <2>
  1296. MyResource writeResource(...)
  1297. @PreAuthorize("hasAuthority('db') and hasRole('ADMIN')") <3>
  1298. MyResource deleteResource(...)
  1299. @PreAuthorize("principal.claims['aud'] == 'my-audience'") <4>
  1300. MyResource readResource(...);
  1301. @PreAuthorize("@authz.check(authentication, #root)")
  1302. MyResource shareResource(...);
  1303. }
  1304. ----
  1305. Kotlin::
  1306. +
  1307. [source,kotlin,role="secondary"]
  1308. ----
  1309. @Component
  1310. open class MyService {
  1311. @PreAuthorize("denyAll") <1>
  1312. fun myDeprecatedMethod(...): MyResource
  1313. @PreAuthorize("hasRole('ADMIN')") <2>
  1314. fun writeResource(...): MyResource
  1315. @PreAuthorize("hasAuthority('db') and hasRole('ADMIN')") <3>
  1316. fun deleteResource(...): MyResource
  1317. @PreAuthorize("principal.claims['aud'] == 'my-audience'") <4>
  1318. fun readResource(...): MyResource
  1319. @PreAuthorize("@authz.check(#root)")
  1320. fun shareResource(...): MyResource
  1321. }
  1322. ----
  1323. Xml::
  1324. +
  1325. [source,xml,role="secondary"]
  1326. ----
  1327. <sec:method-security>
  1328. <protect-pointcut expression="execution(* com.mycompany.*Service.myDeprecatedMethod(..))" access="denyAll"/> <1>
  1329. <protect-pointcut expression="execution(* com.mycompany.*Service.writeResource(..))" access="hasRole('ADMIN')"/> <2>
  1330. <protect-pointcut expression="execution(* com.mycompany.*Service.deleteResource(..))" access="hasAuthority('db') and hasRole('ADMIN')"/> <3>
  1331. <protect-pointcut expression="execution(* com.mycompany.*Service.readResource(..))" access="principal.claims['aud'] == 'my-audience'"/> <4>
  1332. <protect-pointcut expression="execution(* com.mycompany.*Service.shareResource(..))" access="@authz.check(#root)"/> <5>
  1333. </sec:method-security>
  1334. ----
  1335. ======
  1336. <1> This method may not be invoked by anyone for any reason
  1337. <2> This method may only be invoked by ``Authentication``s granted the `ROLE_ADMIN` authority
  1338. <3> This method may only be invoked by ``Authentication``s granted the `db` and `ROLE_ADMIN` authorities
  1339. <4> This method may only be invoked by ``Princpal``s with an `aud` claim equal to "my-audience"
  1340. <5> This method may only be invoked if the bean ``authz``'s `check` method returns `true`
  1341. [[using_method_parameters]]
  1342. === Using Method Parameters
  1343. Additionally, Spring Security provides a mechanism for discovering method parameters so they can also be accessed in the SpEL expression as well.
  1344. For a complete reference, Spring Security uses `DefaultSecurityParameterNameDiscoverer` to discover the parameter names.
  1345. By default, the following options are tried for a method.
  1346. 1. If Spring Security's `@P` annotation is present on a single argument to the method, the value is used.
  1347. The following example uses the `@P` annotation:
  1348. +
  1349. [tabs]
  1350. ======
  1351. Java::
  1352. +
  1353. [source,java,role="primary"]
  1354. ----
  1355. import org.springframework.security.access.method.P;
  1356. ...
  1357. @PreAuthorize("hasPermission(#c, 'write')")
  1358. public void updateContact(@P("c") Contact contact);
  1359. ----
  1360. Kotlin::
  1361. +
  1362. [source,kotlin,role="secondary"]
  1363. ----
  1364. import org.springframework.security.access.method.P
  1365. ...
  1366. @PreAuthorize("hasPermission(#c, 'write')")
  1367. fun doSomething(@P("c") contact: Contact?)
  1368. ----
  1369. ======
  1370. +
  1371. The intention of this expression is to require that the current `Authentication` have `write` permission specifically for this `Contact` instance.
  1372. +
  1373. Behind the scenes, this is implemented by using `AnnotationParameterNameDiscoverer`, which you can customize to support the value attribute of any specified annotation.
  1374. * 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.
  1375. The following example uses the `@Param` annotation:
  1376. +
  1377. [tabs]
  1378. ======
  1379. Java::
  1380. +
  1381. [source,java,role="primary"]
  1382. ----
  1383. import org.springframework.data.repository.query.Param;
  1384. ...
  1385. @PreAuthorize("#n == authentication.name")
  1386. Contact findContactByName(@Param("n") String name);
  1387. ----
  1388. Kotlin::
  1389. +
  1390. [source,kotlin,role="secondary"]
  1391. ----
  1392. import org.springframework.data.repository.query.Param
  1393. ...
  1394. @PreAuthorize("#n == authentication.name")
  1395. fun findContactByName(@Param("n") name: String?): Contact?
  1396. ----
  1397. ======
  1398. +
  1399. The intention of this expression is to require that `name` be equal to `Authentication#getName` for the invocation to be authorized.
  1400. +
  1401. Behind the scenes, this is implemented by using `AnnotationParameterNameDiscoverer`, which you can customize to support the value attribute of any specified annotation.
  1402. * If you compile your code with the `-parameters` argument, the standard JDK reflection API is used to discover the parameter names.
  1403. This works on both classes and interfaces.
  1404. * Finally, if you compile your code with debug symbols, the parameter names are discovered by using the debug symbols.
  1405. This does not work for interfaces, since they do not have debug information about the parameter names.
  1406. For interfaces, either annotations or the `-parameters` approach must be used.
  1407. [[authorize-object]]
  1408. == Authorizing Arbitrary Objects
  1409. Spring Security also supports wrapping any object that is annotated its method security annotations.
  1410. The simplest way to achieve this is to mark any method that returns the object you wish to authorize with the `@AuthorizeReturnObject` annotation.
  1411. For example, consider the following `User` class:
  1412. [tabs]
  1413. ======
  1414. Java::
  1415. +
  1416. [source,java,role="primary"]
  1417. ----
  1418. public class User {
  1419. private String name;
  1420. private String email;
  1421. public User(String name, String email) {
  1422. this.name = name;
  1423. this.email = email;
  1424. }
  1425. public String getName() {
  1426. return this.name;
  1427. }
  1428. @PreAuthorize("hasAuthority('user:read')")
  1429. public String getEmail() {
  1430. return this.email;
  1431. }
  1432. }
  1433. ----
  1434. Kotlin::
  1435. +
  1436. [source,kotlin,role="secondary"]
  1437. ----
  1438. class User (val name:String, @get:PreAuthorize("hasAuthority('user:read')") val email:String)
  1439. ----
  1440. ======
  1441. Given an interface like this one:
  1442. [tabs]
  1443. ======
  1444. Java::
  1445. +
  1446. [source,java,role="primary"]
  1447. ----
  1448. public class UserRepository {
  1449. @AuthorizeReturnObject
  1450. Optional<User> findByName(String name) {
  1451. // ...
  1452. }
  1453. }
  1454. ----
  1455. Kotlin::
  1456. +
  1457. [source,kotlin,role="secondary"]
  1458. ----
  1459. class UserRepository {
  1460. @AuthorizeReturnObject
  1461. fun findByName(name:String?): Optional<User?>? {
  1462. // ...
  1463. }
  1464. }
  1465. ----
  1466. ======
  1467. Then any `User` that is returned from `findById` will be secured like other Spring Security-protected components:
  1468. [tabs]
  1469. ======
  1470. Java::
  1471. +
  1472. [source,java,role="primary"]
  1473. ----
  1474. @Autowired
  1475. UserRepository users;
  1476. @Test
  1477. void getEmailWhenProxiedThenAuthorizes() {
  1478. Optional<User> securedUser = users.findByName("name");
  1479. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> securedUser.get().getEmail());
  1480. }
  1481. ----
  1482. Kotlin::
  1483. +
  1484. [source,kotlin,role="secondary"]
  1485. ----
  1486. import jdk.incubator.vector.VectorOperators.Test
  1487. import java.nio.file.AccessDeniedException
  1488. import java.util.*
  1489. @Autowired
  1490. var users:UserRepository? = null
  1491. @Test
  1492. fun getEmailWhenProxiedThenAuthorizes() {
  1493. val securedUser: Optional<User> = users.findByName("name")
  1494. assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy{securedUser.get().getEmail()}
  1495. }
  1496. ----
  1497. ======
  1498. [NOTE]
  1499. ====
  1500. `@AuthorizeReturnObject` can be placed at the class level. Note, though, that this means Spring Security will proxy any return object, including ``String``, ``Integer`` and other types.
  1501. This is often not what you want to do.
  1502. In most cases, you will want to annotate the individual methods.
  1503. ====
  1504. === Programmatically Proxying
  1505. You can also programmatically proxy a given object.
  1506. To achieve this, you can autowire the provided `AuthorizationProxyFactory` instance, which is based on which method security interceptors you have configured.
  1507. If you are using `@EnableMethodSecurity`, then this means that it will by default have the interceptors for `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter`.
  1508. You can proxy an instance of user in the following way:
  1509. [tabs]
  1510. ======
  1511. Java::
  1512. +
  1513. [source,java,role="primary"]
  1514. ----
  1515. @Autowired
  1516. AuthorizationProxyFactory proxyFactory;
  1517. @Test
  1518. void getEmailWhenProxiedThenAuthorizes() {
  1519. User user = new User("name", "email");
  1520. assertThat(user.getEmail()).isNotNull();
  1521. User securedUser = proxyFactory.proxy(user);
  1522. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(securedUser::getEmail);
  1523. }
  1524. ----
  1525. Kotlin::
  1526. +
  1527. [source,kotlin,role="secondary"]
  1528. ----
  1529. @Autowired
  1530. var proxyFactory:AuthorizationProxyFactory? = null
  1531. @Test
  1532. fun getEmailWhenProxiedThenAuthorizes() {
  1533. val user: User = User("name", "email")
  1534. assertThat(user.getEmail()).isNotNull()
  1535. val securedUser: User = proxyFactory.proxy(user)
  1536. assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy(securedUser::getEmail)
  1537. }
  1538. ----
  1539. ======
  1540. === Manual Construction
  1541. You can also define your own instance if you need something different from the Spring Security default.
  1542. For example, if you define an `AuthorizationProxyFactory` instance like so:
  1543. [tabs]
  1544. ======
  1545. Java::
  1546. +
  1547. [source,java,role="primary"]
  1548. ----
  1549. import static org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor.preAuthorize;
  1550. // ...
  1551. AuthorizationProxyFactory proxyFactory = new AuthorizationProxyFactory(preAuthorize());
  1552. ----
  1553. Kotlin::
  1554. +
  1555. [source,kotlin,role="secondary"]
  1556. ----
  1557. import org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor.preAuthorize
  1558. // ...
  1559. val proxyFactory: AuthorizationProxyFactory = AuthorizationProxyFactory(preAuthorize())
  1560. ----
  1561. ======
  1562. Then you can wrap any instance of `User` as follows:
  1563. [tabs]
  1564. ======
  1565. Java::
  1566. +
  1567. [source,java,role="primary"]
  1568. ----
  1569. @Test
  1570. void getEmailWhenProxiedThenAuthorizes() {
  1571. AuthorizationProxyFactory proxyFactory = new AuthorizationProxyFactory(preAuthorize());
  1572. User user = new User("name", "email");
  1573. assertThat(user.getEmail()).isNotNull();
  1574. User securedUser = proxyFactory.proxy(user);
  1575. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(securedUser::getEmail);
  1576. }
  1577. ----
  1578. Kotlin::
  1579. +
  1580. [source,kotlin,role="secondary"]
  1581. ----
  1582. @Test
  1583. fun getEmailWhenProxiedThenAuthorizes() {
  1584. val proxyFactory: AuthorizationProxyFactory = AuthorizationProxyFactory(preAuthorize())
  1585. val user: User = User("name", "email")
  1586. assertThat(user.getEmail()).isNotNull()
  1587. val securedUser: User = proxyFactory.proxy(user)
  1588. assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy(securedUser::getEmail)
  1589. }
  1590. ----
  1591. ======
  1592. [NOTE]
  1593. ====
  1594. This feature does not yet support Spring AOT
  1595. ====
  1596. === Proxying Collections
  1597. `AuthorizationProxyFactory` supports Java collections, streams, arrays, optionals, and iterators by proxying the element type and maps by proxying the value type.
  1598. This means that when proxying a `List` of objects, the following also works:
  1599. [tabs]
  1600. ======
  1601. Java::
  1602. +
  1603. [source,java,role="primary"]
  1604. ----
  1605. @Test
  1606. void getEmailWhenProxiedThenAuthorizes() {
  1607. AuthorizationProxyFactory proxyFactory = new AuthorizationProxyFactory(preAuthorize());
  1608. List<User> users = List.of(ada, albert, marie);
  1609. List<User> securedUsers = proxyFactory.proxy(users);
  1610. securedUsers.forEach((securedUser) ->
  1611. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(securedUser::getEmail));
  1612. }
  1613. ----
  1614. ======
  1615. === Proxying Classes
  1616. In limited circumstances, it may be valuable to proxy a `Class` itself, and `AuthorizationProxyFactory` also supports this.
  1617. This is roughly the equivalent of calling `ProxyFactory#getProxyClass` in Spring Framework's support for creating proxies.
  1618. One place where this is handy is when you need to construct the proxy class ahead-of-time, like with Spring AOT.
  1619. === Support for All Method Security Annotations
  1620. `AuthorizationProxyFactory` supports whichever method security annotations are enabled in your application.
  1621. It is based off of whatever `AuthorizationAdvisor` classes are published as a bean.
  1622. Since `@EnableMethodSecurity` publishes `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` advisors by default, you will typically need to do nothing to activate the ability.
  1623. [NOTE]
  1624. ====
  1625. SpEL expressions that use `returnObject` or `filterObject` sit behind the proxy and so have full access to the object.
  1626. ====
  1627. [#custom_advice]
  1628. === Custom Advice
  1629. If you have security advice that you also want applied, you can publish your own `AuthorizationAdvisor` like so:
  1630. [tabs]
  1631. ======
  1632. Java::
  1633. +
  1634. [source,java,role="primary"]
  1635. ----
  1636. @EnableMethodSecurity
  1637. class SecurityConfig {
  1638. @Bean
  1639. static AuthorizationAdvisor myAuthorizationAdvisor() {
  1640. return new AuthorizationAdvisor();
  1641. }
  1642. }
  1643. ----
  1644. Kotlin::
  1645. +
  1646. [source,kotlin,role="secondary"]
  1647. ----
  1648. @EnableMethodSecurity
  1649. internal class SecurityConfig {
  1650. @Bean
  1651. fun myAuthorizationAdvisor(): AuthorizationAdvisor {
  1652. return AuthorizationAdvisor()
  1653. }
  1654. ]
  1655. ----
  1656. ======
  1657. And Spring Security will add that advisor into the set of advice that `AuthorizationProxyFactory` adds when proxying an object.
  1658. === Working with Jackson
  1659. One powerful use of this feature is to return a secured value from a controller like so:
  1660. [tabs]
  1661. ======
  1662. Java::
  1663. +
  1664. [source,java,role="primary"]
  1665. ----
  1666. @RestController
  1667. public class UserController {
  1668. @Autowired
  1669. AuthorizationProxyFactory proxyFactory;
  1670. @GetMapping
  1671. User currentUser(@AuthenticationPrincipal User user) {
  1672. return this.proxyFactory.proxy(user);
  1673. }
  1674. }
  1675. ----
  1676. Kotlin::
  1677. +
  1678. [source,kotlin,role="secondary"]
  1679. ----
  1680. @RestController
  1681. class UserController {
  1682. @Autowired
  1683. var proxyFactory: AuthorizationProxyFactory? = null
  1684. @GetMapping
  1685. fun currentUser(@AuthenticationPrincipal user:User?): User {
  1686. return proxyFactory.proxy(user)
  1687. }
  1688. }
  1689. ----
  1690. ======
  1691. If you are using Jackson, though, this may result in a serialization error like the following:
  1692. [source,bash]
  1693. ====
  1694. com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Direct self-reference leading to cycle
  1695. ====
  1696. This is due to how Jackson works with CGLIB proxies.
  1697. To address this, add the following annotation to the top of the `User` class:
  1698. [tabs]
  1699. ======
  1700. Java::
  1701. +
  1702. [source,java,role="primary"]
  1703. ----
  1704. @JsonSerialize(as = User.class)
  1705. public class User {
  1706. }
  1707. ----
  1708. Kotlin::
  1709. +
  1710. [source,kotlin,role="secondary"]
  1711. ----
  1712. @JsonSerialize(`as` = User::class)
  1713. class User
  1714. ----
  1715. ======
  1716. Finally, you will need to publish a <<custom_advice, custom interceptor>> to catch the `AccessDeniedException` thrown for each field, which you can do like so:
  1717. [tabs]
  1718. ======
  1719. Java::
  1720. +
  1721. [source,java,role="primary"]
  1722. ----
  1723. @Component
  1724. public class AccessDeniedExceptionInterceptor implements AuthorizationAdvisor {
  1725. private final AuthorizationAdvisor advisor = AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
  1726. @Override
  1727. public Object invoke(MethodInvocation invocation) throws Throwable {
  1728. try {
  1729. return invocation.proceed();
  1730. } catch (AccessDeniedException ex) {
  1731. return null;
  1732. }
  1733. }
  1734. @Override
  1735. public Pointcut getPointcut() {
  1736. return this.advisor.getPointcut();
  1737. }
  1738. @Override
  1739. public Advice getAdvice() {
  1740. return this;
  1741. }
  1742. @Override
  1743. public int getOrder() {
  1744. return this.advisor.getOrder() - 1;
  1745. }
  1746. }
  1747. ----
  1748. Kotlin::
  1749. +
  1750. [source,kotlin,role="secondary"]
  1751. ----
  1752. @Component
  1753. class AccessDeniedExceptionInterceptor: AuthorizationAdvisor {
  1754. var advisor: AuthorizationAdvisor = AuthorizationManagerBeforeMethodInterceptor.preAuthorize()
  1755. @Throws(Throwable::class)
  1756. fun invoke(invocation: MethodInvocation): Any? {
  1757. return try {
  1758. invocation.proceed()
  1759. } catch (ex:AccessDeniedException) {
  1760. null
  1761. }
  1762. }
  1763. val pointcut: Pointcut
  1764. get() = advisor.getPointcut()
  1765. val advice: Advice
  1766. get() = this
  1767. val order: Int
  1768. get() = advisor.getOrder() - 1
  1769. }
  1770. ----
  1771. ======
  1772. Then, you'll see a different JSON serialization based on the authorization level of the user.
  1773. If they don't have the `user:read` authority, then they'll see:
  1774. [source,json]
  1775. ----
  1776. {
  1777. "name" : "name",
  1778. "email" : null
  1779. }
  1780. ----
  1781. And if they do have that authority, they'll see:
  1782. [source,json]
  1783. ----
  1784. {
  1785. "name" : "name",
  1786. "email" : "email"
  1787. }
  1788. ----
  1789. [TIP]
  1790. ====
  1791. You can also add the Spring Boot property `spring.jackson.default-property-inclusion=non_null` to exclude the null value, if you also don't want to reveal the JSON key to an unauthorized user.
  1792. ====
  1793. [[migration-enableglobalmethodsecurity]]
  1794. == Migrating from `@EnableGlobalMethodSecurity`
  1795. If you are using `@EnableGlobalMethodSecurity`, you should migrate to `@EnableMethodSecurity`.
  1796. [[servlet-replace-globalmethodsecurity-with-methodsecurity]]
  1797. === 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]
  1798. {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.
  1799. 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.
  1800. This means that the following two listings are functionally equivalent:
  1801. [tabs]
  1802. ======
  1803. Java::
  1804. +
  1805. [source,java,role="primary"]
  1806. ----
  1807. @EnableGlobalMethodSecurity(prePostEnabled = true)
  1808. ----
  1809. Kotlin::
  1810. +
  1811. [source,kotlin,role="secondary"]
  1812. ----
  1813. @EnableGlobalMethodSecurity(prePostEnabled = true)
  1814. ----
  1815. Xml::
  1816. +
  1817. [source,xml,role="secondary"]
  1818. ----
  1819. <global-method-security pre-post-enabled="true"/>
  1820. ----
  1821. ======
  1822. and:
  1823. [tabs]
  1824. ======
  1825. Java::
  1826. +
  1827. [source,java,role="primary"]
  1828. ----
  1829. @EnableMethodSecurity
  1830. ----
  1831. Kotlin::
  1832. +
  1833. [source,kotlin,role="secondary"]
  1834. ----
  1835. @EnableMethodSecurity
  1836. ----
  1837. Xml::
  1838. +
  1839. [source,xml,role="secondary"]
  1840. ----
  1841. <method-security/>
  1842. ----
  1843. ======
  1844. For applications not using the pre-post annotations, make sure to turn it off to avoid activating unwanted behavior.
  1845. For example, a listing like:
  1846. [tabs]
  1847. ======
  1848. Java::
  1849. +
  1850. [source,java,role="primary"]
  1851. ----
  1852. @EnableGlobalMethodSecurity(securedEnabled = true)
  1853. ----
  1854. Kotlin::
  1855. +
  1856. [source,kotlin,role="secondary"]
  1857. ----
  1858. @EnableGlobalMethodSecurity(securedEnabled = true)
  1859. ----
  1860. Xml::
  1861. +
  1862. [source,xml,role="secondary"]
  1863. ----
  1864. <global-method-security secured-enabled="true"/>
  1865. ----
  1866. ======
  1867. should change to:
  1868. [tabs]
  1869. ======
  1870. Java::
  1871. +
  1872. [source,java,role="primary"]
  1873. ----
  1874. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  1875. ----
  1876. Kotlin::
  1877. +
  1878. [source,kotlin,role="secondary"]
  1879. ----
  1880. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  1881. ----
  1882. Xml::
  1883. +
  1884. [source,xml,role="secondary"]
  1885. ----
  1886. <method-security secured-enabled="true" pre-post-enabled="false"/>
  1887. ----
  1888. ======
  1889. === Use a Custom `@Bean` instead of subclassing `DefaultMethodSecurityExpressionHandler`
  1890. As a performance optimization, a new method was introduced to `MethodSecurityExpressionHandler` that takes a `Supplier<Authentication>` instead of an `Authentication`.
  1891. This allows Spring Security to defer the lookup of the `Authentication`, and is taken advantage of automatically when you use `@EnableMethodSecurity` instead of `@EnableGlobalMethodSecurity`.
  1892. However, let's say that your code extends `DefaultMethodSecurityExpressionHandler` and overrides `createSecurityExpressionRoot(Authentication, MethodInvocation)` to return a custom `SecurityExpressionRoot` instance.
  1893. This will no longer work because the arrangement that `@EnableMethodSecurity` sets up calls `createEvaluationContext(Supplier<Authentication>, MethodInvocation)` instead.
  1894. Happily, such a level of customization is often unnecessary.
  1895. Instead, you can create a custom bean with the authorization methods that you need.
  1896. For example, let's say you are wanting a custom evaluation of `@PostAuthorize("hasAuthority('ADMIN')")`.
  1897. You can create a custom `@Bean` like this one:
  1898. [tabs]
  1899. ======
  1900. Java::
  1901. +
  1902. [source,java,role="primary"]
  1903. ----
  1904. class MyAuthorizer {
  1905. boolean isAdmin(MethodSecurityExpressionOperations root) {
  1906. boolean decision = root.hasAuthority("ADMIN");
  1907. // custom work ...
  1908. return decision;
  1909. }
  1910. }
  1911. ----
  1912. Kotlin::
  1913. +
  1914. [source,kotlin,role="secondary"]
  1915. ----
  1916. class MyAuthorizer {
  1917. fun isAdmin(val root: MethodSecurityExpressionOperations): boolean {
  1918. val decision = root.hasAuthority("ADMIN");
  1919. // custom work ...
  1920. return decision;
  1921. }
  1922. }
  1923. ----
  1924. ======
  1925. and then refer to it in the annotation like so:
  1926. [tabs]
  1927. ======
  1928. Java::
  1929. +
  1930. [source,java,role="primary"]
  1931. ----
  1932. @PreAuthorize("@authz.isAdmin(#root)")
  1933. ----
  1934. Kotlin::
  1935. +
  1936. [source,kotlin,role="secondary"]
  1937. ----
  1938. @PreAuthorize("@authz.isAdmin(#root)")
  1939. ----
  1940. ======
  1941. [[subclass-defaultmethodsecurityexpressionhandler]]
  1942. ==== I'd still prefer to subclass `DefaultMethodSecurityExpressionHandler`
  1943. If you must continue subclassing `DefaultMethodSecurityExpressionHandler`, you can still do so.
  1944. Instead, override the `createEvaluationContext(Supplier<Authentication>, MethodInvocation)` method like so:
  1945. [tabs]
  1946. ======
  1947. Java::
  1948. +
  1949. [source,java,role="primary"]
  1950. ----
  1951. @Component
  1952. class MyExpressionHandler extends DefaultMethodSecurityExpressionHandler {
  1953. @Override
  1954. public EvaluationContext createEvaluationContext(Supplier<Authentication> authentication, MethodInvocation mi) {
  1955. StandardEvaluationContext context = (StandardEvaluationContext) super.createEvaluationContext(authentication, mi);
  1956. MethodSecurityExpressionOperations delegate = (MethodSecurityExpressionOperations) context.getRootObject().getValue();
  1957. MySecurityExpressionRoot root = new MySecurityExpressionRoot(delegate);
  1958. context.setRootObject(root);
  1959. return context;
  1960. }
  1961. }
  1962. ----
  1963. Kotlin::
  1964. +
  1965. [source,kotlin,role="secondary"]
  1966. ----
  1967. @Component
  1968. class MyExpressionHandler: DefaultMethodSecurityExpressionHandler {
  1969. override fun createEvaluationContext(val authentication: Supplier<Authentication>,
  1970. val mi: MethodInvocation): EvaluationContext {
  1971. val context = super.createEvaluationContext(authentication, mi) as StandardEvaluationContext
  1972. val delegate = context.getRootObject().getValue() as MethodSecurityExpressionOperations
  1973. val root = MySecurityExpressionRoot(delegate)
  1974. context.setRootObject(root)
  1975. return context
  1976. }
  1977. }
  1978. ----
  1979. ======
  1980. == Further Reading
  1981. 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.
  1982. 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].