method-security.adoc 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310
  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}reference/using/build-systems.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. * Providing <<fallback-values-authorization-denied,fallback values when authorization is denied>>
  38. * Filtering methods with <<use-prefilter,`@PreFilter`>> and <<use-postfilter,`@PostFilter`>>
  39. * Authorizing methods with <<use-jsr250,JSR-250 annotations>>
  40. * Authorizing methods with <<use-aspectj,AspectJ expressions>>
  41. * Integrating with <<weave-aspectj,AspectJ byte-code weaving>>
  42. * Coordinating with <<changing-the-order,@Transactional and other AOP-based annotations>>
  43. * Customizing <<customizing-expression-handling,SpEL expression handling>>
  44. * Integrating with <<custom-authorization-managers,custom authorization systems>>
  45. [[method-security-architecture]]
  46. == How Method Security Works
  47. Spring Security's method authorization support is handy for:
  48. * Extracting fine-grained authorization logic; for example, when the method parameters and return values contribute to the authorization decision.
  49. * Enforcing security at the service layer
  50. * Stylistically favoring annotation-based over `HttpSecurity`-based configuration
  51. 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.
  52. As already mentioned, you begin by adding `@EnableMethodSecurity` to a `@Configuration` class or `<sec:method-security/>` in a Spring XML configuration file.
  53. [[use-method-security]]
  54. [NOTE]
  55. ====
  56. This annotation and XML element supercede `@EnableGlobalMethodSecurity` and `<sec:global-method-security/>`, respectively.
  57. They offer the following improvements:
  58. 1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters.
  59. This simplifies reuse and customization.
  60. 2. Favors direct bean-based configuration, instead of requiring extending `GlobalMethodSecurityConfiguration` to customize beans
  61. 3. Is built using native Spring AOP, removing abstractions and allowing you to use Spring AOP building blocks to customize
  62. 4. Checks for conflicting annotations to ensure an unambiguous security configuration
  63. 5. Complies with JSR-250
  64. 6. Enables `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` by default
  65. If you are using `@EnableGlobalMethodSecurity` or `<global-method-security/>`, these are now deprecated, and you are encouraged to migrate.
  66. ====
  67. Method authorization is a combination of before- and after-method authorization.
  68. Consider a service bean that is annotated in the following way:
  69. [tabs]
  70. ======
  71. Java::
  72. +
  73. [source,java,role="primary"]
  74. ----
  75. @Service
  76. public class MyCustomerService {
  77. @PreAuthorize("hasAuthority('permission:read')")
  78. @PostAuthorize("returnObject.owner == authentication.name")
  79. public Customer readCustomer(String id) { ... }
  80. }
  81. ----
  82. Kotlin::
  83. +
  84. [source,kotlin,role="secondary"]
  85. ----
  86. @Service
  87. open class MyCustomerService {
  88. @PreAuthorize("hasAuthority('permission:read')")
  89. @PostAuthorize("returnObject.owner == authentication.name")
  90. fun readCustomer(val id: String): Customer { ... }
  91. }
  92. ----
  93. ======
  94. A given invocation to `MyCustomerService#readCustomer` may look something like this when Method Security <<activate-method-security,is activated>>:
  95. image::{figures}/methodsecurity.png[]
  96. 1. Spring AOP invokes its proxy method for `readCustomer`. Among the proxy's other advisors, it invokes an javadoc:org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor[] that matches <<annotation-method-pointcuts,the `@PreAuthorize` pointcut>>
  97. 2. The interceptor invokes javadoc:org.springframework.security.authorization.method.PreAuthorizeAuthorizationManager[`PreAuthorizeAuthorizationManager#check`]
  98. 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`.
  99. 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]
  100. 5. If the evaluation passes, then Spring AOP proceeds to invoke the method.
  101. 6. If not, the interceptor publishes an `AuthorizationDeniedEvent` and throws an javadoc:org.springframework.security.access.AccessDeniedException[] which xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[the `ExceptionTranslationFilter`] catches and returns a 403 status code to the response
  102. 7. After the method returns, Spring AOP invokes an javadoc:org.springframework.security.authorization.method.AuthorizationManagerAfterMethodInterceptor[] that matches <<annotation-method-pointcuts,the `@PostAuthorize` pointcut>>, operating the same as above, but with javadoc:org.springframework.security.authorization.method.PostAuthorizeAuthorizationManager[]
  103. 8. If the evaluation passes (in this case, the return value belongs to the logged-in user), processing continues normally
  104. 9. If not, the interceptor publishes an `AuthorizationDeniedEvent` and throws an javadoc:org.springframework.security.access.AccessDeniedException[], which xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[the `ExceptionTranslationFilter`] catches and returns a 403 status code to the response
  105. [NOTE]
  106. If the method is not being called in the context of an HTTP request, you will likely need to handle the `AccessDeniedException` yourself
  107. [[unanimous-based-authorization-decisions]]
  108. === Multiple Annotations Are Computed In Series
  109. As demonstrated above, if a method invocation involves multiple <<authorizing-with-annotations,Method Security annotations>>, each of those is processed one at a time.
  110. This means that they can collectively be thought of as being "anded" together.
  111. In other words, for an invocation to be authorized, all annotation inspections need to pass authorization.
  112. [[repeated-annotations]]
  113. === Repeated Annotations Are Not Supported
  114. That said, it is not supported to repeat the same annotation on the same method.
  115. For example, you cannot place `@PreAuthorize` twice on the same method.
  116. Instead, use SpEL's boolean support or its support for delegating to a separate bean.
  117. [[annotation-method-pointcuts]]
  118. === Each Annotation Has Its Own Pointcut
  119. 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>>.
  120. // FIXME: AuthorizationMethodPointcuts is package private and Javadoc is not published You can see the specifics of this in javadoc:org.springframework.security.authorization.method.AuthorizationMethodPointcuts[].
  121. [[annotation-method-interceptors]]
  122. === Each Annotation Has Its Own Method Interceptor
  123. Each annotation has its own dedicated method interceptor.
  124. The reason for this is to make things more composable.
  125. For example, if needed, you can disable the Spring Security defaults and <<_enabling_certain_annotations,publish only the `@PostAuthorize` method interceptor>>.
  126. The method interceptors are as follows:
  127. * For <<use-preauthorize,`@PreAuthorize`>>, Spring Security uses javadoc:org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor[`AuthorizationManagerBeforeMethodInterceptor#preAuthorize`], which in turn uses javadoc:org.springframework.security.authorization.method.PreAuthorizeAuthorizationManager[]
  128. * For <<use-postauthorize,`@PostAuthorize`>>, Spring Security uses javadoc:org.springframework.security.authorization.method.AuthorizationManagerAfterMethodInterceptor[`AuthorizationManagerAfterMethodInterceptor#postAuthorize`], which in turn uses javadoc:org.springframework.security.authorization.method.PostAuthorizeAuthorizationManager[]
  129. * For <<use-prefilter,`@PreFilter`>>, Spring Security uses javadoc:org.springframework.security.authorization.method.PreFilterAuthorizationMethodInterceptor[]
  130. * For <<use-postfilter,`@PostFilter`>>, Spring Security uses javadoc:org.springframework.security.authorization.method.PostFilterAuthorizationMethodInterceptor[]
  131. * For <<use-secured,`@Secured`>>, Spring Security uses javadoc:org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor[`AuthorizationManagerBeforeMethodInterceptor#secured`], which in turn uses javadoc:org.springframework.security.authorization.method.SecuredAuthorizationManager[]
  132. * For JSR-250 annotations, Spring Security uses javadoc:org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor[`AuthorizationManagerBeforeMethodInterceptor#jsr250`], which in turn uses javadoc:org.springframework.security.authorization.method.Jsr250AuthorizationManager[]
  133. Generally speaking, you can consider the following listing as representative of what interceptors Spring Security publishes when you add `@EnableMethodSecurity`:
  134. [tabs]
  135. ======
  136. Java::
  137. +
  138. [source,java,role="primary"]
  139. ----
  140. @Bean
  141. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  142. static Advisor preAuthorizeMethodInterceptor() {
  143. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize();
  144. }
  145. @Bean
  146. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  147. static Advisor postAuthorizeMethodInterceptor() {
  148. return AuthorizationManagerAfterMethodInterceptor.postAuthorize();
  149. }
  150. @Bean
  151. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  152. static Advisor preFilterMethodInterceptor() {
  153. return AuthorizationManagerBeforeMethodInterceptor.preFilter();
  154. }
  155. @Bean
  156. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  157. static Advisor postFilterMethodInterceptor() {
  158. return AuthorizationManagerAfterMethodInterceptor.postFilter();
  159. }
  160. ----
  161. ======
  162. [[favor-granting-authorities]]
  163. === Favor Granting Authorities Over Complicated SpEL Expressions
  164. Quite often it can be tempting to introduce a complicated SpEL expression like the following:
  165. [tabs]
  166. ======
  167. Java::
  168. +
  169. [source,java,role="primary"]
  170. ----
  171. @PreAuthorize("hasAuthority('permission:read') || hasRole('ADMIN')")
  172. ----
  173. ======
  174. .Kotlin
  175. [source,kotlin,role="kotlin"]
  176. ----
  177. @PreAuthorize("hasAuthority('permission:read') || hasRole('ADMIN')")
  178. ----
  179. However, you could instead grant `permission:read` to those with `ROLE_ADMIN`.
  180. One way to do this is with a `RoleHierarchy` like so:
  181. [tabs]
  182. ======
  183. Java::
  184. +
  185. [source,java,role="primary"]
  186. ----
  187. @Bean
  188. static RoleHierarchy roleHierarchy() {
  189. return RoleHierarchyImpl.fromHierarchy("ROLE_ADMIN > permission:read");
  190. }
  191. ----
  192. Kotlin::
  193. +
  194. [source,kotlin,role="secondary"]
  195. ----
  196. companion object {
  197. @Bean
  198. fun roleHierarchy(): RoleHierarchy {
  199. return RoleHierarchyImpl.fromHierarchy("ROLE_ADMIN > permission:read")
  200. }
  201. }
  202. ----
  203. Xml::
  204. +
  205. [source,xml,role="secondary"]
  206. ----
  207. <bean id="roleHierarchy"
  208. class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl" factory-method="fromHierarchy">
  209. <constructor-arg value="ROLE_ADMIN > permission:read"/>
  210. </bean>
  211. ----
  212. ======
  213. and then <<customizing-expression-handling,set that in a `MethodSecurityExpressionHandler` instance>>.
  214. This then allows you to have a simpler <<use-preauthorize,`@PreAuthorize`>> expression like this one:
  215. [tabs]
  216. ======
  217. Java::
  218. +
  219. [source,java,role="primary"]
  220. ----
  221. @PreAuthorize("hasAuthority('permission:read')")
  222. ----
  223. Kotlin::
  224. +
  225. [source,kotlin,role="secondary"]
  226. ----
  227. @PreAuthorize("hasAuthority('permission:read')")
  228. ----
  229. ======
  230. Or, where possible, adapt application-specific authorization logic into granted authorities at login time.
  231. [[request-vs-method]]
  232. == Comparing Request-level vs Method-level Authorization
  233. When should you favor method-level authorization over xref:servlet/authorization/authorize-http-requests.adoc[request-level authorization]?
  234. Some of it comes down to taste; however, consider the following strengths list of each to help you decide.
  235. |===
  236. || *request-level* | *method-level*
  237. | *authorization type* | coarse-grained | fine-grained
  238. | *configuration location* | declared in a config class | local to method declaration
  239. | *configuration style* | DSL | Annotations
  240. | *authorization definitions* | programmatic | SpEL
  241. |===
  242. The main tradeoff seems to be where you want your authorization rules to live.
  243. [NOTE]
  244. It's important to remember that when you use annotation-based Method Security, then unannotated methods are not secured.
  245. 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.
  246. [[authorizing-with-annotations]]
  247. == Authorizing with Annotations
  248. The primary way Spring Security enables method-level authorization support is through annotations that you can add to methods, classes, and interfaces.
  249. [[use-preauthorize]]
  250. === Authorizing Method Invocation with `@PreAuthorize`
  251. When <<activate-method-security,Method Security is active>>, you can annotate a method with the javadoc:org.springframework.security.access.prepost.PreAuthorize[format=annotation] annotation like so:
  252. [tabs]
  253. ======
  254. Java::
  255. +
  256. [source,java,role="primary"]
  257. ----
  258. @Component
  259. public class BankService {
  260. @PreAuthorize("hasRole('ADMIN')")
  261. public Account readAccount(Long id) {
  262. // ... is only invoked if the `Authentication` has the `ROLE_ADMIN` authority
  263. }
  264. }
  265. ----
  266. Kotlin::
  267. +
  268. [source,kotlin,role="secondary"]
  269. ----
  270. @Component
  271. open class BankService {
  272. @PreAuthorize("hasRole('ADMIN')")
  273. fun readAccount(val id: Long): Account {
  274. // ... is only invoked if the `Authentication` has the `ROLE_ADMIN` authority
  275. }
  276. }
  277. ----
  278. ======
  279. This is meant to indicate that the method can only be invoked if the provided expression `hasRole('ADMIN')` passes.
  280. You can then xref:servlet/test/method.adoc[test the class] to confirm it is enforcing the authorization rule like so:
  281. [tabs]
  282. ======
  283. Java::
  284. +
  285. [source,java,role="primary"]
  286. ----
  287. @Autowired
  288. BankService bankService;
  289. @WithMockUser(roles="ADMIN")
  290. @Test
  291. void readAccountWithAdminRoleThenInvokes() {
  292. Account account = this.bankService.readAccount("12345678");
  293. // ... assertions
  294. }
  295. @WithMockUser(roles="WRONG")
  296. @Test
  297. void readAccountWithWrongRoleThenAccessDenied() {
  298. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(
  299. () -> this.bankService.readAccount("12345678"));
  300. }
  301. ----
  302. Kotlin::
  303. +
  304. [source,kotlin,role="secondary"]
  305. ----
  306. @WithMockUser(roles="ADMIN")
  307. @Test
  308. fun readAccountWithAdminRoleThenInvokes() {
  309. val account: Account = this.bankService.readAccount("12345678")
  310. // ... assertions
  311. }
  312. @WithMockUser(roles="WRONG")
  313. @Test
  314. fun readAccountWithWrongRoleThenAccessDenied() {
  315. assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy {
  316. this.bankService.readAccount("12345678")
  317. }
  318. }
  319. ----
  320. ======
  321. [TIP]
  322. `@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>>.
  323. 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>>.
  324. [[use-postauthorize]]
  325. === Authorization Method Results with `@PostAuthorize`
  326. When Method Security is active, you can annotate a method with the javadoc:org.springframework.security.access.prepost.PostAuthorize[format=annotation] annotation like so:
  327. [tabs]
  328. ======
  329. Java::
  330. +
  331. [source,java,role="primary"]
  332. ----
  333. @Component
  334. public class BankService {
  335. @PostAuthorize("returnObject.owner == authentication.name")
  336. public Account readAccount(Long id) {
  337. // ... is only returned if the `Account` belongs to the logged in user
  338. }
  339. }
  340. ----
  341. Kotlin::
  342. +
  343. [source,kotlin,role="secondary"]
  344. ----
  345. @Component
  346. open class BankService {
  347. @PostAuthorize("returnObject.owner == authentication.name")
  348. fun readAccount(val id: Long): Account {
  349. // ... is only returned if the `Account` belongs to the logged in user
  350. }
  351. }
  352. ----
  353. ======
  354. This is meant to indicate that the method can only return the value if the provided expression `returnObject.owner == authentication.name` passes.
  355. `returnObject` represents the `Account` object to be returned.
  356. You can then xref:servlet/test/method.adoc[test the class] to confirm it is enforcing the authorization rule:
  357. [tabs]
  358. ======
  359. Java::
  360. +
  361. [source,java,role="primary"]
  362. ----
  363. @Autowired
  364. BankService bankService;
  365. @WithMockUser(username="owner")
  366. @Test
  367. void readAccountWhenOwnedThenReturns() {
  368. Account account = this.bankService.readAccount("12345678");
  369. // ... assertions
  370. }
  371. @WithMockUser(username="wrong")
  372. @Test
  373. void readAccountWhenNotOwnedThenAccessDenied() {
  374. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(
  375. () -> this.bankService.readAccount("12345678"));
  376. }
  377. ----
  378. Kotlin::
  379. +
  380. [source,kotlin,role="secondary"]
  381. ----
  382. @WithMockUser(username="owner")
  383. @Test
  384. fun readAccountWhenOwnedThenReturns() {
  385. val account: Account = this.bankService.readAccount("12345678")
  386. // ... assertions
  387. }
  388. @WithMockUser(username="wrong")
  389. @Test
  390. fun readAccountWhenNotOwnedThenAccessDenied() {
  391. assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy {
  392. this.bankService.readAccount("12345678")
  393. }
  394. }
  395. ----
  396. ======
  397. [TIP]
  398. `@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>>.
  399. `@PostAuthorize` is particularly helpful when defending against https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html[Insecure Direct Object Reference].
  400. In fact, it can be defined as a <<meta-annotations,meta-annotation>> like so:
  401. [tabs]
  402. ======
  403. Java::
  404. +
  405. [source,java,role="primary"]
  406. ----
  407. @Target({ ElementType.METHOD, ElementType.TYPE })
  408. @Retention(RetentionPolicy.RUNTIME)
  409. @PostAuthorize("returnObject.owner == authentication.name")
  410. public @interface RequireOwnership {}
  411. ----
  412. Kotlin::
  413. +
  414. [source,kotlin,role="secondary"]
  415. ----
  416. @Target(ElementType.METHOD, ElementType.TYPE)
  417. @Retention(RetentionPolicy.RUNTIME)
  418. @PostAuthorize("returnObject.owner == authentication.name")
  419. annotation class RequireOwnership
  420. ----
  421. ======
  422. Allowing you to instead annotate the service in the following way:
  423. [tabs]
  424. ======
  425. Java::
  426. +
  427. [source,java,role="primary"]
  428. ----
  429. @Component
  430. public class BankService {
  431. @RequireOwnership
  432. public Account readAccount(Long id) {
  433. // ... is only returned if the `Account` belongs to the logged in user
  434. }
  435. }
  436. ----
  437. Kotlin::
  438. +
  439. [source,kotlin,role="secondary"]
  440. ----
  441. @Component
  442. open class BankService {
  443. @RequireOwnership
  444. fun readAccount(val id: Long): Account {
  445. // ... is only returned if the `Account` belongs to the logged in user
  446. }
  447. }
  448. ----
  449. ======
  450. The result is that the above method will only return the `Account` if its `owner` attribute matches the logged-in user's `name`.
  451. If not, Spring Security will throw an `AccessDeniedException` and return a 403 status code.
  452. [[use-prefilter]]
  453. === Filtering Method Parameters with `@PreFilter`
  454. When Method Security is active, you can annotate a method with the javadoc:org.springframework.security.access.prepost.PreFilter[format=annotation] annotation like so:
  455. [tabs]
  456. ======
  457. Java::
  458. +
  459. [source,java,role="primary"]
  460. ----
  461. @Component
  462. public class BankService {
  463. @PreFilter("filterObject.owner == authentication.name")
  464. public Collection<Account> updateAccounts(Account... accounts) {
  465. // ... `accounts` will only contain the accounts owned by the logged-in user
  466. return updated;
  467. }
  468. }
  469. ----
  470. Kotlin::
  471. +
  472. [source,kotlin,role="secondary"]
  473. ----
  474. @Component
  475. open class BankService {
  476. @PreFilter("filterObject.owner == authentication.name")
  477. fun updateAccounts(vararg accounts: Account): Collection<Account> {
  478. // ... `accounts` will only contain the accounts owned by the logged-in user
  479. return updated
  480. }
  481. }
  482. ----
  483. ======
  484. This is meant to filter out any values from `accounts` where the expression `filterObject.owner == authentication.name` fails.
  485. `filterObject` represents each `account` in `accounts` and is used to test each `account`.
  486. You can then test the class in the following way to confirm it is enforcing the authorization rule:
  487. [tabs]
  488. ======
  489. Java::
  490. +
  491. [source,java,role="primary"]
  492. ----
  493. @Autowired
  494. BankService bankService;
  495. @WithMockUser(username="owner")
  496. @Test
  497. void updateAccountsWhenOwnedThenReturns() {
  498. Account ownedBy = ...
  499. Account notOwnedBy = ...
  500. Collection<Account> updated = this.bankService.updateAccounts(ownedBy, notOwnedBy);
  501. assertThat(updated).containsOnly(ownedBy);
  502. }
  503. ----
  504. Kotlin::
  505. +
  506. [source,kotlin,role="secondary"]
  507. ----
  508. @Autowired
  509. lateinit var bankService: BankService
  510. @WithMockUser(username="owner")
  511. @Test
  512. fun updateAccountsWhenOwnedThenReturns() {
  513. val ownedBy: Account = ...
  514. val notOwnedBy: Account = ...
  515. val updated: Collection<Account> = bankService.updateAccounts(ownedBy, notOwnedBy)
  516. assertThat(updated).containsOnly(ownedBy)
  517. }
  518. ----
  519. ======
  520. [TIP]
  521. `@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>>.
  522. `@PreFilter` supports arrays, collections, maps, and streams (so long as the stream is still open).
  523. For example, the above `updateAccounts` declaration will function the same way as the following other four:
  524. [tabs]
  525. ======
  526. Java::
  527. +
  528. [source,java,role="primary"]
  529. ----
  530. @PreFilter("filterObject.owner == authentication.name")
  531. public Collection<Account> updateAccounts(Account[] accounts)
  532. @PreFilter("filterObject.owner == authentication.name")
  533. public Collection<Account> updateAccounts(Collection<Account> accounts)
  534. @PreFilter("filterObject.value.owner == authentication.name")
  535. public Collection<Account> updateAccounts(Map<String, Account> accounts)
  536. @PreFilter("filterObject.owner == authentication.name")
  537. public Collection<Account> updateAccounts(Stream<Account> accounts)
  538. ----
  539. Kotlin::
  540. +
  541. [source,kotlin,role="secondary"]
  542. ----
  543. @PreFilter("filterObject.owner == authentication.name")
  544. fun updateAccounts(accounts: Array<Account>): Collection<Account>
  545. @PreFilter("filterObject.owner == authentication.name")
  546. fun updateAccounts(accounts: Collection<Account>): Collection<Account>
  547. @PreFilter("filterObject.value.owner == authentication.name")
  548. fun updateAccounts(accounts: Map<String, Account>): Collection<Account>
  549. @PreFilter("filterObject.owner == authentication.name")
  550. fun updateAccounts(accounts: Stream<Account>): Collection<Account>
  551. ----
  552. ======
  553. The result is that the above method will only have the `Account` instances where their `owner` attribute matches the logged-in user's `name`.
  554. [[use-postfilter]]
  555. === Filtering Method Results with `@PostFilter`
  556. When Method Security is active, you can annotate a method with the javadoc:org.springframework.security.access.prepost.PostFilter[format=annotation] annotation like so:
  557. [tabs]
  558. ======
  559. Java::
  560. +
  561. [source,java,role="primary"]
  562. ----
  563. @Component
  564. public class BankService {
  565. @PostFilter("filterObject.owner == authentication.name")
  566. public Collection<Account> readAccounts(String... ids) {
  567. // ... the return value will be filtered to only contain the accounts owned by the logged-in user
  568. return accounts;
  569. }
  570. }
  571. ----
  572. Kotlin::
  573. +
  574. [source,kotlin,role="secondary"]
  575. ----
  576. @Component
  577. open class BankService {
  578. @PreFilter("filterObject.owner == authentication.name")
  579. fun readAccounts(vararg ids: String): Collection<Account> {
  580. // ... the return value will be filtered to only contain the accounts owned by the logged-in user
  581. return accounts
  582. }
  583. }
  584. ----
  585. ======
  586. This is meant to filter out any values from the return value where the expression `filterObject.owner == authentication.name` fails.
  587. `filterObject` represents each `account` in `accounts` and is used to test each `account`.
  588. You can then test the class like so to confirm it is enforcing the authorization rule:
  589. [tabs]
  590. ======
  591. Java::
  592. +
  593. [source,java,role="primary"]
  594. ----
  595. @Autowired
  596. BankService bankService;
  597. @WithMockUser(username="owner")
  598. @Test
  599. void readAccountsWhenOwnedThenReturns() {
  600. Collection<Account> accounts = this.bankService.updateAccounts("owner", "not-owner");
  601. assertThat(accounts).hasSize(1);
  602. assertThat(accounts.get(0).getOwner()).isEqualTo("owner");
  603. }
  604. ----
  605. Kotlin::
  606. +
  607. [source,kotlin,role="secondary"]
  608. ----
  609. @Autowired
  610. lateinit var bankService: BankService
  611. @WithMockUser(username="owner")
  612. @Test
  613. fun readAccountsWhenOwnedThenReturns() {
  614. val accounts: Collection<Account> = bankService.updateAccounts("owner", "not-owner")
  615. assertThat(accounts).hasSize(1)
  616. assertThat(accounts[0].owner).isEqualTo("owner")
  617. }
  618. ----
  619. ======
  620. [TIP]
  621. `@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>>.
  622. `@PostFilter` supports arrays, collections, maps, and streams (so long as the stream is still open).
  623. For example, the above `readAccounts` declaration will function the same way as the following other three:
  624. [tabs]
  625. ======
  626. Java::
  627. +
  628. [source,java,role="primary"]
  629. ----
  630. @PostFilter("filterObject.owner == authentication.name")
  631. public Collection<Account> readAccounts(String... ids)
  632. @PostFilter("filterObject.owner == authentication.name")
  633. public Account[] readAccounts(String... ids)
  634. @PostFilter("filterObject.value.owner == authentication.name")
  635. public Map<String, Account> readAccounts(String... ids)
  636. @PostFilter("filterObject.owner == authentication.name")
  637. public Stream<Account> readAccounts(String... ids)
  638. ----
  639. Kotlin::
  640. +
  641. [source,kotlin,role="secondary"]
  642. ----
  643. @PostFilter("filterObject.owner == authentication.name")
  644. fun readAccounts(vararg ids: String): Collection<Account>
  645. @PostFilter("filterObject.owner == authentication.name")
  646. fun readAccounts(vararg ids: String): Array<Account>
  647. @PostFilter("filterObject.owner == authentication.name")
  648. fun readAccounts(vararg ids: String): Map<String, Account>
  649. @PostFilter("filterObject.owner == authentication.name")
  650. fun readAccounts(vararg ids: String): Stream<Account>
  651. ----
  652. ======
  653. The result is that the above method will return the `Account` instances where their `owner` attribute matches the logged-in user's `name`.
  654. [NOTE]
  655. 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.
  656. [[use-secured]]
  657. === Authorizing Method Invocation with `@Secured`
  658. javadoc:org.springframework.security.access.annotation.Secured[format=annotation] is a legacy option for authorizing invocations.
  659. <<use-preauthorize,`@PreAuthorize`>> supercedes it and is recommended instead.
  660. To use the `@Secured` annotation, you should first change your Method Security declaration to enable it like so:
  661. [tabs]
  662. ======
  663. Java::
  664. +
  665. [source,java,role="primary"]
  666. ----
  667. @EnableMethodSecurity(securedEnabled = true)
  668. ----
  669. Kotlin::
  670. +
  671. [source,kotlin,role="secondary"]
  672. ----
  673. @EnableMethodSecurity(securedEnabled = true)
  674. ----
  675. Xml::
  676. +
  677. [source,xml,role="secondary"]
  678. ----
  679. <sec:method-security secured-enabled="true"/>
  680. ----
  681. ======
  682. This will cause Spring Security to publish <<annotation-method-interceptors,the corresponding method interceptor>> that authorizes methods, classes, and interfaces annotated with `@Secured`.
  683. [[use-jsr250]]
  684. === Authorizing Method Invocation with JSR-250 Annotations
  685. In case you would like to use https://jcp.org/en/jsr/detail?id=250[JSR-250] annotations, Spring Security also supports that.
  686. <<use-preauthorize,`@PreAuthorize`>> has more expressive power and is thus recommended.
  687. To use the JSR-250 annotations, you should first change your Method Security declaration to enable them like so:
  688. [tabs]
  689. ======
  690. Java::
  691. +
  692. [source,java,role="primary"]
  693. ----
  694. @EnableMethodSecurity(jsr250Enabled = true)
  695. ----
  696. Kotlin::
  697. +
  698. [source,kotlin,role="secondary"]
  699. ----
  700. @EnableMethodSecurity(jsr250Enabled = true)
  701. ----
  702. Xml::
  703. +
  704. [source,xml,role="secondary"]
  705. ----
  706. <sec:method-security jsr250-enabled="true"/>
  707. ----
  708. ======
  709. 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`.
  710. [[class-or-interface-annotations]]
  711. === Declaring Annotations at the Class or Interface Level
  712. It's also supported to have Method Security annotations at the class and interface level.
  713. If it is at the class level like so:
  714. [tabs]
  715. ======
  716. Java::
  717. +
  718. [source,java,role="primary"]
  719. ----
  720. @Controller
  721. @PreAuthorize("hasAuthority('ROLE_USER')")
  722. public class MyController {
  723. @GetMapping("/endpoint")
  724. public String endpoint() { ... }
  725. }
  726. ----
  727. Kotlin::
  728. +
  729. [source,kotlin,role="secondary"]
  730. ----
  731. @Controller
  732. @PreAuthorize("hasAuthority('ROLE_USER')")
  733. open class MyController {
  734. @GetMapping("/endpoint")
  735. fun endpoint(): String { ... }
  736. }
  737. ----
  738. ======
  739. then all methods inherit the class-level behavior.
  740. Or, if it's declared like the following at both the class and method level:
  741. [tabs]
  742. ======
  743. Java::
  744. +
  745. [source,java,role="primary"]
  746. ----
  747. @Controller
  748. @PreAuthorize("hasAuthority('ROLE_USER')")
  749. public class MyController {
  750. @GetMapping("/endpoint")
  751. @PreAuthorize("hasAuthority('ROLE_ADMIN')")
  752. public String endpoint() { ... }
  753. }
  754. ----
  755. Kotlin::
  756. +
  757. [source,kotlin,role="secondary"]
  758. ----
  759. @Controller
  760. @PreAuthorize("hasAuthority('ROLE_USER')")
  761. open class MyController {
  762. @GetMapping("/endpoint")
  763. @PreAuthorize("hasAuthority('ROLE_ADMIN')")
  764. fun endpoint(): String { ... }
  765. }
  766. ----
  767. ======
  768. then methods declaring the annotation override the class-level annotation.
  769. The same is true for interfaces, with the exception that if a class inherits the annotation from two different interfaces, then startup will fail.
  770. This is because Spring Security has no way to tell which one you want to use.
  771. In cases like this, you can resolve the ambiguity by adding the annotation to the concrete method.
  772. [[meta-annotations]]
  773. === Using Meta Annotations
  774. Method Security supports meta annotations.
  775. This means that you can take any annotation and improve readability based on your application-specific use cases.
  776. For example, you can simplify `@PreAuthorize("hasRole('ADMIN')")` to `@IsAdmin` like so:
  777. [tabs]
  778. ======
  779. Java::
  780. +
  781. [source,java,role="primary"]
  782. ----
  783. @Target({ ElementType.METHOD, ElementType.TYPE })
  784. @Retention(RetentionPolicy.RUNTIME)
  785. @PreAuthorize("hasRole('ADMIN')")
  786. public @interface IsAdmin {}
  787. ----
  788. Kotlin::
  789. +
  790. [source,kotlin,role="secondary"]
  791. ----
  792. @Target(ElementType.METHOD, ElementType.TYPE)
  793. @Retention(RetentionPolicy.RUNTIME)
  794. @PreAuthorize("hasRole('ADMIN')")
  795. annotation class IsAdmin
  796. ----
  797. ======
  798. And the result is that on your secured methods you can now do the following instead:
  799. [tabs]
  800. ======
  801. Java::
  802. +
  803. [source,java,role="primary"]
  804. ----
  805. @Component
  806. public class BankService {
  807. @IsAdmin
  808. public Account readAccount(Long id) {
  809. // ... is only returned if the `Account` belongs to the logged in user
  810. }
  811. }
  812. ----
  813. Kotlin::
  814. +
  815. [source,kotlin,role="secondary"]
  816. ----
  817. @Component
  818. open class BankService {
  819. @IsAdmin
  820. fun readAccount(val id: Long): Account {
  821. // ... is only returned if the `Account` belongs to the logged in user
  822. }
  823. }
  824. ----
  825. ======
  826. This results in more readable method definitions.
  827. ==== Templating Meta-Annotation Expressions
  828. You can also opt into using meta-annotation templates, which allow for much more powerful annotation definitions.
  829. First, publish the following bean:
  830. [tabs]
  831. ======
  832. Java::
  833. +
  834. [source,java,role="primary"]
  835. ----
  836. @Bean
  837. static AnnotationTemplateExpressionDefaults templateExpressionDefaults() {
  838. return new AnnotationTemplateExpressionDefaults();
  839. }
  840. ----
  841. Kotlin::
  842. +
  843. [source,kotlin,role="secondary"]
  844. ----
  845. companion object {
  846. @Bean
  847. fun templateExpressionDefaults(): AnnotationTemplateExpressionDefaults {
  848. return AnnotationTemplateExpressionDefaults()
  849. }
  850. }
  851. ----
  852. ======
  853. Now instead of `@IsAdmin`, you can create something more powerful like `@HasRole` like so:
  854. [tabs]
  855. ======
  856. Java::
  857. +
  858. [source,java,role="primary"]
  859. ----
  860. @Target({ ElementType.METHOD, ElementType.TYPE })
  861. @Retention(RetentionPolicy.RUNTIME)
  862. @PreAuthorize("hasRole('{value}')")
  863. public @interface HasRole {
  864. String value();
  865. }
  866. ----
  867. Kotlin::
  868. +
  869. [source,kotlin,role="secondary"]
  870. ----
  871. @Target(ElementType.METHOD, ElementType.TYPE)
  872. @Retention(RetentionPolicy.RUNTIME)
  873. @PreAuthorize("hasRole('{value}')")
  874. annotation class HasRole(val value: String)
  875. ----
  876. ======
  877. And the result is that on your secured methods you can now do the following instead:
  878. [tabs]
  879. ======
  880. Java::
  881. +
  882. [source,java,role="primary"]
  883. ----
  884. @Component
  885. public class BankService {
  886. @HasRole("ADMIN")
  887. public Account readAccount(Long id) {
  888. // ... is only returned if the `Account` belongs to the logged in user
  889. }
  890. }
  891. ----
  892. Kotlin::
  893. +
  894. [source,kotlin,role="secondary"]
  895. ----
  896. @Component
  897. open class BankService {
  898. @HasRole("ADMIN")
  899. fun readAccount(val id: Long): Account {
  900. // ... is only returned if the `Account` belongs to the logged in user
  901. }
  902. }
  903. ----
  904. ======
  905. 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.
  906. For example, consider the following `@HasAnyRole` annotation:
  907. [tabs]
  908. ======
  909. Java::
  910. +
  911. [source,java,role="primary"]
  912. ----
  913. @Target({ ElementType.METHOD, ElementType.TYPE })
  914. @Retention(RetentionPolicy.RUNTIME)
  915. @PreAuthorize("hasAnyRole({roles})")
  916. public @interface HasAnyRole {
  917. String[] roles();
  918. }
  919. ----
  920. Kotlin::
  921. +
  922. [source,kotlin,role="secondary"]
  923. ----
  924. @Target(ElementType.METHOD, ElementType.TYPE)
  925. @Retention(RetentionPolicy.RUNTIME)
  926. @PreAuthorize("hasAnyRole({roles})")
  927. annotation class HasAnyRole(val roles: Array<String>)
  928. ----
  929. ======
  930. 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:
  931. [tabs]
  932. ======
  933. Java::
  934. +
  935. [source,java,role="primary"]
  936. ----
  937. @Component
  938. public class BankService {
  939. @HasAnyRole(roles = { "'USER'", "'ADMIN'" })
  940. public Account readAccount(Long id) {
  941. // ... is only returned if the `Account` belongs to the logged in user
  942. }
  943. }
  944. ----
  945. Kotlin::
  946. +
  947. [source,kotlin,role="secondary"]
  948. ----
  949. @Component
  950. open class BankService {
  951. @HasAnyRole(roles = arrayOf("'USER'", "'ADMIN'"))
  952. fun readAccount(val id: Long): Account {
  953. // ... is only returned if the `Account` belongs to the logged in user
  954. }
  955. }
  956. ----
  957. ======
  958. so that, once replaced, the expression becomes `@PreAuthorize("hasAnyRole('USER', 'ADMIN')")`.
  959. [[enable-annotation]]
  960. === Enabling Certain Annotations
  961. You can turn off ``@EnableMethodSecurity``'s pre-configuration and replace it with you own.
  962. You may choose to do this if you want to <<custom-authorization-managers,customize the `AuthorizationManager`>> or `Pointcut`.
  963. Or you may simply want to only enable a specific annotation, like `@PostAuthorize`.
  964. You can do this in the following way:
  965. .Only @PostAuthorize Configuration
  966. [tabs]
  967. ======
  968. Java::
  969. +
  970. [source,java,role="primary"]
  971. ----
  972. @Configuration
  973. @EnableMethodSecurity(prePostEnabled = false)
  974. class MethodSecurityConfig {
  975. @Bean
  976. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  977. Advisor postAuthorize() {
  978. return AuthorizationManagerAfterMethodInterceptor.postAuthorize();
  979. }
  980. }
  981. ----
  982. Kotlin::
  983. +
  984. [source,kotlin,role="secondary"]
  985. ----
  986. @Configuration
  987. @EnableMethodSecurity(prePostEnabled = false)
  988. class MethodSecurityConfig {
  989. @Bean
  990. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  991. fun postAuthorize() : Advisor {
  992. return AuthorizationManagerAfterMethodInterceptor.postAuthorize()
  993. }
  994. }
  995. ----
  996. Xml::
  997. +
  998. [source,xml,role="secondary"]
  999. ----
  1000. <sec:method-security pre-post-enabled="false"/>
  1001. <aop:config/>
  1002. <bean id="postAuthorize"
  1003. class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor"
  1004. factory-method="postAuthorize"/>
  1005. ----
  1006. ======
  1007. The above snippet achieves this by first disabling Method Security's pre-configurations and then publishing <<annotation-method-interceptors, the `@PostAuthorize` interceptor>> itself.
  1008. [[use-intercept-methods]]
  1009. == Authorizing with `<intercept-methods>`
  1010. 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.
  1011. 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:
  1012. [tabs]
  1013. ======
  1014. Xml::
  1015. +
  1016. [source,xml,role="primary"]
  1017. ----
  1018. <bean class="org.mycompany.MyController">
  1019. <intercept-methods>
  1020. <protect method="get*" access="hasAuthority('read')"/>
  1021. <protect method="*" access="hasAuthority('write')"/>
  1022. </intercept-methods>
  1023. </bean>
  1024. ----
  1025. ======
  1026. [NOTE]
  1027. This only supports matching method by prefix or by name.
  1028. If your needs are more complex than that, <<authorizing-with-annotations,use annotation support>> instead.
  1029. [[use-programmatic-authorization]]
  1030. == Authorizing Methods Programmatically
  1031. As you've already seen, there are several ways that you can specify non-trivial authorization rules using <<authorization-expressions, Method Security SpEL expressions>>.
  1032. There are a number of ways that you can instead allow your logic to be Java-based instead of SpEL-based.
  1033. This gives use access the entire Java language for increased testability and flow control.
  1034. === Using a Custom Bean in SpEL
  1035. The first way to authorize a method programmatically is a two-step process.
  1036. First, declare a bean that has a method that takes a `MethodSecurityExpressionOperations` instance like the following:
  1037. [tabs]
  1038. ======
  1039. Java::
  1040. +
  1041. [source,java,role="primary"]
  1042. ----
  1043. @Component("authz")
  1044. public class AuthorizationLogic {
  1045. public boolean decide(MethodSecurityExpressionOperations operations) {
  1046. // ... authorization logic
  1047. }
  1048. }
  1049. ----
  1050. Kotlin::
  1051. +
  1052. [source,kotlin,role="secondary"]
  1053. ----
  1054. @Component("authz")
  1055. open class AuthorizationLogic {
  1056. fun decide(val operations: MethodSecurityExpressionOperations): boolean {
  1057. // ... authorization logic
  1058. }
  1059. }
  1060. ----
  1061. ======
  1062. Then, reference that bean in your annotations in the following way:
  1063. [tabs]
  1064. ======
  1065. Java::
  1066. +
  1067. [source,java,role="primary"]
  1068. ----
  1069. @Controller
  1070. public class MyController {
  1071. @PreAuthorize("@authz.decide(#root)")
  1072. @GetMapping("/endpoint")
  1073. public String endpoint() {
  1074. // ...
  1075. }
  1076. }
  1077. ----
  1078. Kotlin::
  1079. +
  1080. [source,kotlin,role="secondary"]
  1081. ----
  1082. @Controller
  1083. open class MyController {
  1084. @PreAuthorize("@authz.decide(#root)")
  1085. @GetMapping("/endpoint")
  1086. fun String endpoint() {
  1087. // ...
  1088. }
  1089. }
  1090. ----
  1091. ======
  1092. Spring Security will invoke the given method on that bean for each method invocation.
  1093. 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.
  1094. It also has access to the full Java language.
  1095. [TIP]
  1096. In addition to returning a `Boolean`, you can also return `null` to indicate that the code abstains from making a decision.
  1097. If you want to include more information about the nature of the decision, you can instead return a custom `AuthorizationDecision` like this:
  1098. [tabs]
  1099. ======
  1100. Java::
  1101. +
  1102. [source,java,role="primary"]
  1103. ----
  1104. @Component("authz")
  1105. public class AuthorizationLogic {
  1106. public AuthorizationDecision decide(MethodSecurityExpressionOperations operations) {
  1107. // ... authorization logic
  1108. return new MyAuthorizationDecision(false, details);
  1109. }
  1110. }
  1111. ----
  1112. Kotlin::
  1113. +
  1114. [source,kotlin,role="secondary"]
  1115. ----
  1116. @Component("authz")
  1117. open class AuthorizationLogic {
  1118. fun decide(val operations: MethodSecurityExpressionOperations): AuthorizationDecision {
  1119. // ... authorization logic
  1120. return MyAuthorizationDecision(false, details)
  1121. }
  1122. }
  1123. ----
  1124. ======
  1125. Or throw a custom `AuthorizationDeniedException` instance.
  1126. Note, though, that returning an object is preferred as this doesn't incur the expense of generating a stacktrace.
  1127. Then, you can access the custom details when you <<fallback-values-authorization-denied, customize how the authorization result is handled>>.
  1128. [[custom-authorization-managers]]
  1129. === Using a Custom Authorization Manager
  1130. The second way to authorize a method programmatically is to create a custom xref:servlet/authorization/architecture.adoc#_the_authorizationmanager[`AuthorizationManager`].
  1131. First, declare an authorization manager instance, perhaps like this one:
  1132. [tabs]
  1133. ======
  1134. Java::
  1135. +
  1136. [source,java,role="primary"]
  1137. ----
  1138. @Component
  1139. public class MyAuthorizationManager implements AuthorizationManager<MethodInvocation>, AuthorizationManager<MethodInvocationResult> {
  1140. @Override
  1141. public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocation invocation) {
  1142. // ... authorization logic
  1143. }
  1144. @Override
  1145. public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocationResult invocation) {
  1146. // ... authorization logic
  1147. }
  1148. }
  1149. ----
  1150. Kotlin::
  1151. +
  1152. [source,kotlin,role="secondary"]
  1153. ----
  1154. @Component
  1155. class MyAuthorizationManager : AuthorizationManager<MethodInvocation>, AuthorizationManager<MethodInvocationResult> {
  1156. override fun check(authentication: Supplier<Authentication>, invocation: MethodInvocation): AuthorizationDecision {
  1157. // ... authorization logic
  1158. }
  1159. override fun check(authentication: Supplier<Authentication>, invocation: MethodInvocationResult): AuthorizationDecision {
  1160. // ... authorization logic
  1161. }
  1162. }
  1163. ----
  1164. ======
  1165. Then, publish the method interceptor with a pointcut that corresponds to when you want that `AuthorizationManager` to run.
  1166. For example, you could replace how `@PreAuthorize` and `@PostAuthorize` work like so:
  1167. .Only @PreAuthorize and @PostAuthorize Configuration
  1168. [tabs]
  1169. ======
  1170. Java::
  1171. +
  1172. [source,java,role="primary"]
  1173. ----
  1174. @Configuration
  1175. @EnableMethodSecurity(prePostEnabled = false)
  1176. class MethodSecurityConfig {
  1177. @Bean
  1178. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1179. Advisor preAuthorize(MyAuthorizationManager manager) {
  1180. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(manager);
  1181. }
  1182. @Bean
  1183. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1184. Advisor postAuthorize(MyAuthorizationManager manager) {
  1185. return AuthorizationManagerAfterMethodInterceptor.postAuthorize(manager);
  1186. }
  1187. }
  1188. ----
  1189. Kotlin::
  1190. +
  1191. [source,kotlin,role="secondary"]
  1192. ----
  1193. @Configuration
  1194. @EnableMethodSecurity(prePostEnabled = false)
  1195. class MethodSecurityConfig {
  1196. @Bean
  1197. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1198. fun preAuthorize(val manager: MyAuthorizationManager) : Advisor {
  1199. return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(manager)
  1200. }
  1201. @Bean
  1202. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1203. fun postAuthorize(val manager: MyAuthorizationManager) : Advisor {
  1204. return AuthorizationManagerAfterMethodInterceptor.postAuthorize(manager)
  1205. }
  1206. }
  1207. ----
  1208. Xml::
  1209. +
  1210. [source,xml,role="secondary"]
  1211. ----
  1212. <sec:method-security pre-post-enabled="false"/>
  1213. <aop:config/>
  1214. <bean id="preAuthorize"
  1215. class="org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor"
  1216. factory-method="preAuthorize">
  1217. <constructor-arg ref="myAuthorizationManager"/>
  1218. </bean>
  1219. <bean id="postAuthorize"
  1220. class="org.springframework.security.authorization.method.AuthorizationManagerAfterMethodInterceptor"
  1221. factory-method="postAuthorize">
  1222. <constructor-arg ref="myAuthorizationManager"/>
  1223. </bean>
  1224. ----
  1225. ======
  1226. [TIP]
  1227. ====
  1228. You can place your interceptor in between Spring Security method interceptors using the order constants specified in `AuthorizationInterceptorsOrder`.
  1229. ====
  1230. [[customizing-expression-handling]]
  1231. === Customizing Expression Handling
  1232. Or, third, you can customize how each SpEL expression is handled.
  1233. To do that, you can expose a custom javadoc:org.springframework.security.access.expression.method.MethodSecurityExpressionHandler[], like so:
  1234. .Custom MethodSecurityExpressionHandler
  1235. [tabs]
  1236. ======
  1237. Java::
  1238. +
  1239. [source,java,role="primary"]
  1240. ----
  1241. @Bean
  1242. static MethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) {
  1243. DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
  1244. handler.setRoleHierarchy(roleHierarchy);
  1245. return handler;
  1246. }
  1247. ----
  1248. Kotlin::
  1249. +
  1250. [source,kotlin,role="secondary"]
  1251. ----
  1252. companion object {
  1253. @Bean
  1254. fun methodSecurityExpressionHandler(val roleHierarchy: RoleHierarchy) : MethodSecurityExpressionHandler {
  1255. val handler = DefaultMethodSecurityExpressionHandler()
  1256. handler.setRoleHierarchy(roleHierarchy)
  1257. return handler
  1258. }
  1259. }
  1260. ----
  1261. Xml::
  1262. +
  1263. [source,xml,role="secondary"]
  1264. ----
  1265. <sec:method-security>
  1266. <sec:expression-handler ref="myExpressionHandler"/>
  1267. </sec:method-security>
  1268. <bean id="myExpressionHandler"
  1269. class="org.springframework.security.messaging.access.expression.DefaultMessageSecurityExpressionHandler">
  1270. <property name="roleHierarchy" ref="roleHierarchy"/>
  1271. </bean>
  1272. ----
  1273. ======
  1274. [TIP]
  1275. ====
  1276. We expose `MethodSecurityExpressionHandler` using a `static` method to ensure that Spring publishes it before it initializes Spring Security's method security `@Configuration` classes
  1277. ====
  1278. You can also <<subclass-defaultmethodsecurityexpressionhandler,subclass `DefaultMessageSecurityExpressionHandler`>> to add your own custom authorization expressions beyond the defaults.
  1279. [[pre-post-authorize-aot]]
  1280. === Working with AOT
  1281. Spring Security will scan all beans in the application context for methods that use `@PreAuthorize` or `@PostAuthorize`.
  1282. When it finds one, it will resolve any beans used inside the security expression and register the appropriate runtime hints for that bean.
  1283. If it finds a method that uses `@AuthorizeReturnObject`, it will recursively search inside the method's return type for `@PreAuthorize` and `@PostAuthorize` annotations and register them accordingly.
  1284. For example, consider the following Spring Boot application:
  1285. [tabs]
  1286. ======
  1287. Java::
  1288. +
  1289. [source,java,role="primary"]
  1290. ----
  1291. @Service
  1292. public class AccountService { <1>
  1293. @PreAuthorize("@authz.decide()") <2>
  1294. @AuthorizeReturnObject <3>
  1295. public Account getAccountById(String accountId) {
  1296. // ...
  1297. }
  1298. }
  1299. public class Account {
  1300. private final String accountNumber;
  1301. // ...
  1302. @PreAuthorize("@accountAuthz.canViewAccountNumber()") <4>
  1303. public String getAccountNumber() {
  1304. return this.accountNumber;
  1305. }
  1306. @AuthorizeReturnObject <5>
  1307. public User getUser() {
  1308. return new User("John Doe");
  1309. }
  1310. }
  1311. public class User {
  1312. private final String fullName;
  1313. // ...
  1314. @PostAuthorize("@myOtherAuthz.decide()") <6>
  1315. public String getFullName() {
  1316. return this.fullName;
  1317. }
  1318. }
  1319. ----
  1320. Kotlin::
  1321. +
  1322. [source,kotlin,role="secondary"]
  1323. ----
  1324. @Service
  1325. class AccountService { <1>
  1326. @PreAuthorize("@authz.decide()") <2>
  1327. @AuthorizeReturnObject <3>
  1328. fun getAccountById(accountId: String): Account {
  1329. // ...
  1330. }
  1331. }
  1332. class Account(private val accountNumber: String) {
  1333. @PreAuthorize("@accountAuthz.canViewAccountNumber()") <4>
  1334. fun getAccountNumber(): String {
  1335. return this.accountNumber
  1336. }
  1337. @AuthorizeReturnObject <5>
  1338. fun getUser(): User {
  1339. return User("John Doe")
  1340. }
  1341. }
  1342. class User(private val fullName: String) {
  1343. @PostAuthorize("@myOtherAuthz.decide()") <6>
  1344. fun getFullName(): String {
  1345. return this.fullName
  1346. }
  1347. }
  1348. ----
  1349. ======
  1350. <1> Spring Security finds the `AccountService` bean
  1351. <2> Finding a method that uses `@PreAuthorize`, it will resolve any bean names used inside the expression, `authz` in that case, and register runtime hints for the bean class
  1352. <3> Finding a method that uses `@AuthorizeReturnObject`, it will look into the method's return type for any `@PreAuthorize` or `@PostAuthorize`
  1353. <4> Then, it finds a `@PreAuthorize` with another bean name: `accountAuthz`; the runtime hints are registered for the bean class as well
  1354. <5> Finding another `@AuthorizeReturnObject` it will look again into the method's return type
  1355. <6> Now, a `@PostAuthorize` is found with yet another bean name used: `myOtherAuthz`; the runtime hints are registered for the bean class as well
  1356. There will be many times when Spring Security cannot determine the actual return type of the method ahead of time since it may be hidden in an erased generic type.
  1357. Consider the following service:
  1358. [tabs]
  1359. ======
  1360. Java::
  1361. +
  1362. [source,java,role="primary"]
  1363. ----
  1364. @Service
  1365. public class AccountService {
  1366. @AuthorizeReturnObject
  1367. public List<Account> getAllAccounts() {
  1368. // ...
  1369. }
  1370. }
  1371. ----
  1372. Kotlin::
  1373. +
  1374. [source,kotlin,role="secondary"]
  1375. ----
  1376. @Service
  1377. class AccountService {
  1378. @AuthorizeReturnObject
  1379. fun getAllAccounts(): List<Account> {
  1380. // ...
  1381. }
  1382. }
  1383. ----
  1384. ======
  1385. In this case, the generic type is erased and so it isn’t apparent to Spring Security ahead-of-time that `Account` needs to be visited in order to check for `@PreAuthorize` and `@PostAuthorize`.
  1386. To address this, you can publish a javadoc:org.springframework.security.aot.hint.PrePostAuthorizeExpressionBeanHintsRegistrar[`PrePostAuthorizeExpressionBeanHintsRegistrar`] like so:
  1387. [tabs]
  1388. ======
  1389. Java::
  1390. +
  1391. [source,java,role="primary"]
  1392. ----
  1393. @Bean
  1394. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1395. static SecurityHintsRegistrar registerTheseToo() {
  1396. return new PrePostAuthorizeExpressionBeanHintsRegistrar(Account.class);
  1397. }
  1398. ----
  1399. Kotlin::
  1400. +
  1401. [source,kotlin,role="secondary"]
  1402. ----
  1403. @Bean
  1404. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1405. fun registerTheseToo(): SecurityHintsRegistrar {
  1406. return PrePostAuthorizeExpressionBeanHintsRegistrar(Account::class.java)
  1407. }
  1408. ----
  1409. ======
  1410. [[use-aspectj]]
  1411. == Authorizing with AspectJ
  1412. [[match-by-pointcut]]
  1413. === Matching Methods with Custom Pointcuts
  1414. 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].
  1415. This has the potential advantage of centralizing method-level authorization rules.
  1416. 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:
  1417. [tabs]
  1418. ======
  1419. Java::
  1420. +
  1421. [source,java,role="primary"]
  1422. ----
  1423. import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole
  1424. @Bean
  1425. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1426. static Advisor protectServicePointcut() {
  1427. AspectJExpressionPointcut pattern = new AspectJExpressionPointcut()
  1428. pattern.setExpression("execution(* com.mycompany.*Service.*(..))")
  1429. return new AuthorizationManagerBeforeMethodInterceptor(pattern, hasRole("USER"))
  1430. }
  1431. ----
  1432. Kotlin::
  1433. +
  1434. [source,kotlin,role="secondary"]
  1435. ----
  1436. import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole
  1437. companion object {
  1438. @Bean
  1439. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  1440. fun protectServicePointcut(): Advisor {
  1441. val pattern = AspectJExpressionPointcut()
  1442. pattern.setExpression("execution(* com.mycompany.*Service.*(..))")
  1443. return new AuthorizationManagerBeforeMethodInterceptor(pattern, hasRole("USER"))
  1444. }
  1445. }
  1446. ----
  1447. Xml::
  1448. +
  1449. [source,xml,role="secondary"]
  1450. ----
  1451. <sec:method-security>
  1452. <protect-pointcut expression="execution(* com.mycompany.*Service.*(..))" access="hasRole('USER')"/>
  1453. </sec:method-security>
  1454. ----
  1455. ======
  1456. [[weave-aspectj]]
  1457. === Integrate with AspectJ Byte-weaving
  1458. Performance can at times be enhanced by using AspectJ to weave Spring Security advice into the byte code of your beans.
  1459. After setting up AspectJ, you can quite simply state in the `@EnableMethodSecurity` annotation or `<method-security>` element that you are using AspectJ:
  1460. [tabs]
  1461. ======
  1462. Java::
  1463. +
  1464. [source,java,role="primary"]
  1465. ----
  1466. @EnableMethodSecurity(mode=AdviceMode.ASPECTJ)
  1467. ----
  1468. Kotlin::
  1469. +
  1470. [source,kotlin,role="secondary"]
  1471. ----
  1472. @EnableMethodSecurity(mode=AdviceMode.ASPECTJ)
  1473. ----
  1474. Xml::
  1475. +
  1476. [source,xml,role="secondary"]
  1477. ----
  1478. <sec:method-security mode="aspectj"/>
  1479. ----
  1480. ======
  1481. And the result will be that Spring Security will publish its advisors as AspectJ advice so that they can be woven in accordingly.
  1482. [[changing-the-order]]
  1483. == Specifying Order
  1484. 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.
  1485. Namely, the `@PreFilter` method interceptor's order is 100, ``@PreAuthorize``'s is 200, and so on.
  1486. 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`.
  1487. In other words, they are located at the end of the advisor chain by default.
  1488. At times, it can be valuable to have other advice execute before Spring Security.
  1489. 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.
  1490. To get `@EnableTransactionManagement` to open a transaction before method authorization advice runs, you can set ``@EnableTransactionManagement``'s order like so:
  1491. [tabs]
  1492. ======
  1493. Java::
  1494. +
  1495. [source,java,role="primary"]
  1496. ----
  1497. @EnableTransactionManagement(order = 0)
  1498. ----
  1499. Kotlin::
  1500. +
  1501. [source,kotlin,role="secondary"]
  1502. ----
  1503. @EnableTransactionManagement(order = 0)
  1504. ----
  1505. Xml::
  1506. +
  1507. [source,xml,role="secondary"]
  1508. ----
  1509. <tx:annotation-driven ref="txManager" order="0"/>
  1510. ----
  1511. ======
  1512. 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.
  1513. [[authorization-expressions]]
  1514. == Expressing Authorization with SpEL
  1515. You've already seen several examples using SpEL, so now let's cover the API a bit more in depth.
  1516. Spring Security encapsulates all of its authorization fields and methods in a set of root objects.
  1517. The most generic root object is called `SecurityExpressionRoot` and it forms the basis for `MethodSecurityExpressionRoot`.
  1518. Spring Security supplies this root object to `MethodSecurityEvaluationContext` when preparing to evaluate an authorization expression.
  1519. [[using-authorization-expression-fields-and-methods]]
  1520. === Using Authorization Expression Fields and Methods
  1521. The first thing this provides is an enhanced set of authorization fields and methods to your SpEL expressions.
  1522. What follows is a quick overview of the most common methods:
  1523. * `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
  1524. * `denyAll` - The method is not allowed under any circumstances; note that in this case, the `Authentication` is never retrieved from the session
  1525. * `hasAuthority` - The method requires that the `Authentication` have xref:servlet/authorization/architecture.adoc#authz-authorities[a `GrantedAuthority`] that matches the given value
  1526. * `hasRole` - A shortcut for `hasAuthority` that prefixes `ROLE_` or whatever is configured as the default prefix
  1527. * `hasAnyAuthority` - The method requires that the `Authentication` have a `GrantedAuthority` that matches any of the given values
  1528. * `hasAnyRole` - A shortcut for `hasAnyAuthority` that prefixes `ROLE_` or whatever is configured as the default prefix
  1529. * `hasPermission` - A hook into your `PermissionEvaluator` instance for doing object-level authorization
  1530. And here is a brief look at the most common fields:
  1531. * `authentication` - The `Authentication` instance associated with this method invocation
  1532. * `principal` - The `Authentication#getPrincipal` associated with this method invocation
  1533. 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:
  1534. .Authorize Requests
  1535. [tabs]
  1536. ======
  1537. Java::
  1538. +
  1539. [source,java,role="primary"]
  1540. ----
  1541. @Component
  1542. public class MyService {
  1543. @PreAuthorize("denyAll") <1>
  1544. MyResource myDeprecatedMethod(...);
  1545. @PreAuthorize("hasRole('ADMIN')") <2>
  1546. MyResource writeResource(...)
  1547. @PreAuthorize("hasAuthority('db') and hasRole('ADMIN')") <3>
  1548. MyResource deleteResource(...)
  1549. @PreAuthorize("principal.claims['aud'] == 'my-audience'") <4>
  1550. MyResource readResource(...);
  1551. @PreAuthorize("@authz.check(authentication, #root)")
  1552. MyResource shareResource(...);
  1553. }
  1554. ----
  1555. Kotlin::
  1556. +
  1557. [source,kotlin,role="secondary"]
  1558. ----
  1559. @Component
  1560. open class MyService {
  1561. @PreAuthorize("denyAll") <1>
  1562. fun myDeprecatedMethod(...): MyResource
  1563. @PreAuthorize("hasRole('ADMIN')") <2>
  1564. fun writeResource(...): MyResource
  1565. @PreAuthorize("hasAuthority('db') and hasRole('ADMIN')") <3>
  1566. fun deleteResource(...): MyResource
  1567. @PreAuthorize("principal.claims['aud'] == 'my-audience'") <4>
  1568. fun readResource(...): MyResource
  1569. @PreAuthorize("@authz.check(#root)")
  1570. fun shareResource(...): MyResource
  1571. }
  1572. ----
  1573. Xml::
  1574. +
  1575. [source,xml,role="secondary"]
  1576. ----
  1577. <sec:method-security>
  1578. <protect-pointcut expression="execution(* com.mycompany.*Service.myDeprecatedMethod(..))" access="denyAll"/> <1>
  1579. <protect-pointcut expression="execution(* com.mycompany.*Service.writeResource(..))" access="hasRole('ADMIN')"/> <2>
  1580. <protect-pointcut expression="execution(* com.mycompany.*Service.deleteResource(..))" access="hasAuthority('db') and hasRole('ADMIN')"/> <3>
  1581. <protect-pointcut expression="execution(* com.mycompany.*Service.readResource(..))" access="principal.claims['aud'] == 'my-audience'"/> <4>
  1582. <protect-pointcut expression="execution(* com.mycompany.*Service.shareResource(..))" access="@authz.check(#root)"/> <5>
  1583. </sec:method-security>
  1584. ----
  1585. ======
  1586. <1> This method may not be invoked by anyone for any reason
  1587. <2> This method may only be invoked by ``Authentication``s granted the `ROLE_ADMIN` authority
  1588. <3> This method may only be invoked by ``Authentication``s granted the `db` and `ROLE_ADMIN` authorities
  1589. <4> This method may only be invoked by ``Princpal``s with an `aud` claim equal to "my-audience"
  1590. <5> This method may only be invoked if the bean ``authz``'s `check` method returns `true`
  1591. [TIP]
  1592. ====
  1593. You can use a bean like `authz` above to <<_using_a_custom_bean_in_spel, add programmatic authorization>>.
  1594. ====
  1595. [[using_method_parameters]]
  1596. === Using Method Parameters
  1597. Additionally, Spring Security provides a mechanism for discovering method parameters so they can also be accessed in the SpEL expression as well.
  1598. For a complete reference, Spring Security uses `DefaultSecurityParameterNameDiscoverer` to discover the parameter names.
  1599. By default, the following options are tried for a method.
  1600. 1. If Spring Security's `@P` annotation is present on a single argument to the method, the value is used.
  1601. The following example uses the `@P` annotation:
  1602. +
  1603. [tabs]
  1604. ======
  1605. Java::
  1606. +
  1607. [source,java,role="primary"]
  1608. ----
  1609. import org.springframework.security.access.method.P;
  1610. ...
  1611. @PreAuthorize("hasPermission(#c, 'write')")
  1612. public void updateContact(@P("c") Contact contact);
  1613. ----
  1614. Kotlin::
  1615. +
  1616. [source,kotlin,role="secondary"]
  1617. ----
  1618. import org.springframework.security.access.method.P
  1619. ...
  1620. @PreAuthorize("hasPermission(#c, 'write')")
  1621. fun doSomething(@P("c") contact: Contact?)
  1622. ----
  1623. ======
  1624. +
  1625. The intention of this expression is to require that the current `Authentication` have `write` permission specifically for this `Contact` instance.
  1626. +
  1627. Behind the scenes, this is implemented by using `AnnotationParameterNameDiscoverer`, which you can customize to support the value attribute of any specified annotation.
  1628. 2. 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.
  1629. The following example uses the `@Param` annotation:
  1630. +
  1631. [tabs]
  1632. ======
  1633. Java::
  1634. +
  1635. [source,java,role="primary"]
  1636. ----
  1637. import org.springframework.data.repository.query.Param;
  1638. ...
  1639. @PreAuthorize("#n == authentication.name")
  1640. Contact findContactByName(@Param("n") String name);
  1641. ----
  1642. Kotlin::
  1643. +
  1644. [source,kotlin,role="secondary"]
  1645. ----
  1646. import org.springframework.data.repository.query.Param
  1647. ...
  1648. @PreAuthorize("#n == authentication.name")
  1649. fun findContactByName(@Param("n") name: String?): Contact?
  1650. ----
  1651. ======
  1652. +
  1653. The intention of this expression is to require that `name` be equal to `Authentication#getName` for the invocation to be authorized.
  1654. +
  1655. Behind the scenes, this is implemented by using `AnnotationParameterNameDiscoverer`, which you can customize to support the value attribute of any specified annotation.
  1656. 3. If you compile your code with the `-parameters` argument, the standard JDK reflection API is used to discover the parameter names.
  1657. This works on both classes and interfaces.
  1658. 4. Finally, if you compile your code with debug symbols, the parameter names are discovered by using the debug symbols.
  1659. This does not work for interfaces, since they do not have debug information about the parameter names.
  1660. For interfaces, either annotations or the `-parameters` approach must be used.
  1661. [[authorize-object]]
  1662. == Authorizing Arbitrary Objects
  1663. Spring Security also supports wrapping any object that is annotated its method security annotations.
  1664. The simplest way to achieve this is to mark any method that returns the object you wish to authorize with the `@AuthorizeReturnObject` annotation.
  1665. For example, consider the following `User` class:
  1666. [tabs]
  1667. ======
  1668. Java::
  1669. +
  1670. [source,java,role="primary"]
  1671. ----
  1672. public class User {
  1673. private String name;
  1674. private String email;
  1675. public User(String name, String email) {
  1676. this.name = name;
  1677. this.email = email;
  1678. }
  1679. public String getName() {
  1680. return this.name;
  1681. }
  1682. @PreAuthorize("hasAuthority('user:read')")
  1683. public String getEmail() {
  1684. return this.email;
  1685. }
  1686. }
  1687. ----
  1688. Kotlin::
  1689. +
  1690. [source,kotlin,role="secondary"]
  1691. ----
  1692. class User (val name:String, @get:PreAuthorize("hasAuthority('user:read')") val email:String)
  1693. ----
  1694. ======
  1695. Given an interface like this one:
  1696. [tabs]
  1697. ======
  1698. Java::
  1699. +
  1700. [source,java,role="primary"]
  1701. ----
  1702. public class UserRepository {
  1703. @AuthorizeReturnObject
  1704. Optional<User> findByName(String name) {
  1705. // ...
  1706. }
  1707. }
  1708. ----
  1709. Kotlin::
  1710. +
  1711. [source,kotlin,role="secondary"]
  1712. ----
  1713. class UserRepository {
  1714. @AuthorizeReturnObject
  1715. fun findByName(name:String?): Optional<User?>? {
  1716. // ...
  1717. }
  1718. }
  1719. ----
  1720. ======
  1721. Then any `User` that is returned from `findById` will be secured like other Spring Security-protected components:
  1722. [tabs]
  1723. ======
  1724. Java::
  1725. +
  1726. [source,java,role="primary"]
  1727. ----
  1728. @Autowired
  1729. UserRepository users;
  1730. @Test
  1731. void getEmailWhenProxiedThenAuthorizes() {
  1732. Optional<User> securedUser = users.findByName("name");
  1733. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> securedUser.get().getEmail());
  1734. }
  1735. ----
  1736. Kotlin::
  1737. +
  1738. [source,kotlin,role="secondary"]
  1739. ----
  1740. import jdk.incubator.vector.VectorOperators.Test
  1741. import java.nio.file.AccessDeniedException
  1742. import java.util.*
  1743. @Autowired
  1744. var users:UserRepository? = null
  1745. @Test
  1746. fun getEmailWhenProxiedThenAuthorizes() {
  1747. val securedUser: Optional<User> = users.findByName("name")
  1748. assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy{securedUser.get().getEmail()}
  1749. }
  1750. ----
  1751. ======
  1752. === Using `@AuthorizeReturnObject` at the class level
  1753. `@AuthorizeReturnObject` can be placed at the class level. Note, though, that this means Spring Security will attempt to proxy any return object, including ``String``, ``Integer`` and other types.
  1754. This is often not what you want to do.
  1755. If you want to use `@AuthorizeReturnObject` on a class or interface whose methods return value types, like `int`, `String`, `Double` or collections of those types, then you should also publish the appropriate `AuthorizationAdvisorProxyFactory.TargetVisitor` as follows:
  1756. [tabs]
  1757. ======
  1758. Java::
  1759. +
  1760. [source,java,role="primary"]
  1761. ----
  1762. @Bean
  1763. static Customizer<AuthorizationAdvisorProxyFactory> skipValueTypes() {
  1764. return (factory) -> factory.setTargetVisitor(TargetVisitor.defaultsSkipValueTypes());
  1765. }
  1766. ----
  1767. Kotlin::
  1768. +
  1769. [source,kotlin,role="secondary"]
  1770. ----
  1771. @Bean
  1772. open fun skipValueTypes() = Customizer<AuthorizationAdvisorProxyFactory> {
  1773. it.setTargetVisitor(TargetVisitor.defaultsSkipValueTypes())
  1774. }
  1775. ----
  1776. ======
  1777. [TIP]
  1778. ====
  1779. You can set your own `AuthorizationAdvisorProxyFactory.TargetVisitor` to customize the proxying for any set of types
  1780. ====
  1781. === Programmatically Proxying
  1782. You can also programmatically proxy a given object.
  1783. To achieve this, you can autowire the provided `AuthorizationProxyFactory` instance, which is based on which method security interceptors you have configured.
  1784. If you are using `@EnableMethodSecurity`, then this means that it will by default have the interceptors for `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter`.
  1785. You can proxy an instance of user in the following way:
  1786. [tabs]
  1787. ======
  1788. Java::
  1789. +
  1790. [source,java,role="primary"]
  1791. ----
  1792. @Autowired
  1793. AuthorizationProxyFactory proxyFactory;
  1794. @Test
  1795. void getEmailWhenProxiedThenAuthorizes() {
  1796. User user = new User("name", "email");
  1797. assertThat(user.getEmail()).isNotNull();
  1798. User securedUser = proxyFactory.proxy(user);
  1799. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(securedUser::getEmail);
  1800. }
  1801. ----
  1802. Kotlin::
  1803. +
  1804. [source,kotlin,role="secondary"]
  1805. ----
  1806. @Autowired
  1807. var proxyFactory:AuthorizationProxyFactory? = null
  1808. @Test
  1809. fun getEmailWhenProxiedThenAuthorizes() {
  1810. val user: User = User("name", "email")
  1811. assertThat(user.getEmail()).isNotNull()
  1812. val securedUser: User = proxyFactory.proxy(user)
  1813. assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy(securedUser::getEmail)
  1814. }
  1815. ----
  1816. ======
  1817. === Manual Construction
  1818. You can also define your own instance if you need something different from the Spring Security default.
  1819. For example, if you define an `AuthorizationProxyFactory` instance like so:
  1820. [tabs]
  1821. ======
  1822. Java::
  1823. +
  1824. [source,java,role="primary"]
  1825. ----
  1826. import org.springframework.security.authorization.method.AuthorizationAdvisorProxyFactory.TargetVisitor;
  1827. import static org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor.preAuthorize;
  1828. // ...
  1829. AuthorizationProxyFactory proxyFactory = AuthorizationAdvisorProxyFactory.withDefaults();
  1830. // and if needing to skip value types
  1831. proxyFactory.setTargetVisitor(TargetVisitor.defaultsSkipValueTypes());
  1832. ----
  1833. Kotlin::
  1834. +
  1835. [source,kotlin,role="secondary"]
  1836. ----
  1837. import org.springframework.security.authorization.method.AuthorizationAdvisorProxyFactory.TargetVisitor;
  1838. import org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor.preAuthorize
  1839. // ...
  1840. val proxyFactory: AuthorizationProxyFactory = AuthorizationProxyFactory(preAuthorize())
  1841. // and if needing to skip value types
  1842. proxyFactory.setTargetVisitor(TargetVisitor.defaultsSkipValueTypes())
  1843. ----
  1844. ======
  1845. Then you can wrap any instance of `User` as follows:
  1846. [tabs]
  1847. ======
  1848. Java::
  1849. +
  1850. [source,java,role="primary"]
  1851. ----
  1852. @Test
  1853. void getEmailWhenProxiedThenAuthorizes() {
  1854. AuthorizationProxyFactory proxyFactory = AuthorizationAdvisorProxyFactory.withDefaults();
  1855. User user = new User("name", "email");
  1856. assertThat(user.getEmail()).isNotNull();
  1857. User securedUser = proxyFactory.proxy(user);
  1858. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(securedUser::getEmail);
  1859. }
  1860. ----
  1861. Kotlin::
  1862. +
  1863. [source,kotlin,role="secondary"]
  1864. ----
  1865. @Test
  1866. fun getEmailWhenProxiedThenAuthorizes() {
  1867. val proxyFactory: AuthorizationProxyFactory = AuthorizationAdvisorProxyFactory.withDefaults()
  1868. val user: User = User("name", "email")
  1869. assertThat(user.getEmail()).isNotNull()
  1870. val securedUser: User = proxyFactory.proxy(user)
  1871. assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy(securedUser::getEmail)
  1872. }
  1873. ----
  1874. ======
  1875. === Proxying Collections
  1876. `AuthorizationProxyFactory` supports Java collections, streams, arrays, optionals, and iterators by proxying the element type and maps by proxying the value type.
  1877. This means that when proxying a `List` of objects, the following also works:
  1878. [tabs]
  1879. ======
  1880. Java::
  1881. +
  1882. [source,java,role="primary"]
  1883. ----
  1884. @Test
  1885. void getEmailWhenProxiedThenAuthorizes() {
  1886. AuthorizationProxyFactory proxyFactory = AuthorizationAdvisorProxyFactory.withDefaults();
  1887. List<User> users = List.of(ada, albert, marie);
  1888. List<User> securedUsers = proxyFactory.proxy(users);
  1889. securedUsers.forEach((securedUser) ->
  1890. assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(securedUser::getEmail));
  1891. }
  1892. ----
  1893. ======
  1894. === Proxying Classes
  1895. In limited circumstances, it may be valuable to proxy a `Class` itself, and `AuthorizationProxyFactory` also supports this.
  1896. This is roughly the equivalent of calling `ProxyFactory#getProxyClass` in Spring Framework's support for creating proxies.
  1897. One place where this is handy is when you need to construct the proxy class ahead-of-time, like with Spring AOT.
  1898. === Support for All Method Security Annotations
  1899. `AuthorizationProxyFactory` supports whichever method security annotations are enabled in your application.
  1900. It is based off of whatever `AuthorizationAdvisor` classes are published as a bean.
  1901. Since `@EnableMethodSecurity` publishes `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` advisors by default, you will typically need to do nothing to activate the ability.
  1902. [NOTE]
  1903. ====
  1904. SpEL expressions that use `returnObject` or `filterObject` sit behind the proxy and so have full access to the object.
  1905. ====
  1906. [#custom_advice]
  1907. === Custom Advice
  1908. If you have security advice that you also want applied, you can publish your own `AuthorizationAdvisor` like so:
  1909. [tabs]
  1910. ======
  1911. Java::
  1912. +
  1913. [source,java,role="primary"]
  1914. ----
  1915. @EnableMethodSecurity
  1916. class SecurityConfig {
  1917. @Bean
  1918. static AuthorizationAdvisor myAuthorizationAdvisor() {
  1919. return new AuthorizationAdvisor();
  1920. }
  1921. }
  1922. ----
  1923. Kotlin::
  1924. +
  1925. [source,kotlin,role="secondary"]
  1926. ----
  1927. @EnableMethodSecurity
  1928. internal class SecurityConfig {
  1929. @Bean
  1930. fun myAuthorizationAdvisor(): AuthorizationAdvisor {
  1931. return AuthorizationAdvisor()
  1932. }
  1933. ]
  1934. ----
  1935. ======
  1936. And Spring Security will add that advisor into the set of advice that `AuthorizationProxyFactory` adds when proxying an object.
  1937. === Working with Jackson
  1938. One powerful use of this feature is to return a secured value from a controller like so:
  1939. [tabs]
  1940. ======
  1941. Java::
  1942. +
  1943. [source,java,role="primary"]
  1944. ----
  1945. @RestController
  1946. public class UserController {
  1947. @Autowired
  1948. AuthorizationProxyFactory proxyFactory;
  1949. @GetMapping
  1950. User currentUser(@AuthenticationPrincipal User user) {
  1951. return this.proxyFactory.proxy(user);
  1952. }
  1953. }
  1954. ----
  1955. Kotlin::
  1956. +
  1957. [source,kotlin,role="secondary"]
  1958. ----
  1959. @RestController
  1960. class UserController {
  1961. @Autowired
  1962. var proxyFactory: AuthorizationProxyFactory? = null
  1963. @GetMapping
  1964. fun currentUser(@AuthenticationPrincipal user:User?): User {
  1965. return proxyFactory.proxy(user)
  1966. }
  1967. }
  1968. ----
  1969. ======
  1970. You will need to <<fallback-values-authorization-denied,add a `MethodAuthorizationDeniedHandler`>> like this one:
  1971. [tabs]
  1972. ======
  1973. Java::
  1974. +
  1975. [source,java,role="primary"]
  1976. ----
  1977. @Component
  1978. public class Null implements MethodAuthorizationDeniedHandler {
  1979. @Override
  1980. public Object handleDeniedInvocation(MethodInvocation methodInvocation, AuthorizationResult authorizationResult) {
  1981. return null;
  1982. }
  1983. }
  1984. // ...
  1985. @HandleAuthorizationDenied(handlerClass = Null.class)
  1986. public class User {
  1987. ...
  1988. }
  1989. ----
  1990. Kotlin::
  1991. +
  1992. [source,kotlin,role="secondary"]
  1993. ----
  1994. @Component
  1995. class Null : MethodAuthorizationDeniedHandler {
  1996. override fun handleDeniedInvocation(methodInvocation: MethodInvocation?, authorizationResult: AuthorizationResult?): Any? {
  1997. return null
  1998. }
  1999. }
  2000. // ...
  2001. @HandleAuthorizationDenied(handlerClass = Null.class)
  2002. open class User {
  2003. ...
  2004. }
  2005. ----
  2006. ======
  2007. Then, you'll see a different JSON serialization based on the authorization level of the user.
  2008. If they don't have the `user:read` authority, then they'll see:
  2009. [source,json]
  2010. ----
  2011. {
  2012. "name" : "name",
  2013. "email" : null
  2014. }
  2015. ----
  2016. And if they do have that authority, they'll see:
  2017. [source,json]
  2018. ----
  2019. {
  2020. "name" : "name",
  2021. "email" : "email"
  2022. }
  2023. ----
  2024. [TIP]
  2025. ====
  2026. You can also add the Spring Boot property `spring.jackson.default-property-inclusion=non_null` to exclude the null value from serialization, if you also don't want to reveal the JSON key to an unauthorized user.
  2027. ====
  2028. [[authorize-return-object-aot]]
  2029. === Working with AOT
  2030. Spring Security will scan all beans in the application context for methods that use `@AuthorizeReturnObject`.
  2031. When it finds one, it will create and register the appropriate proxy class ahead of time.
  2032. It will also recursively search for other nested objects that also use `@AuthorizeReturnObject` and register them accordingly.
  2033. For example, consider the following Spring Boot application:
  2034. [tabs]
  2035. ======
  2036. Java::
  2037. +
  2038. [source,java,role="primary"]
  2039. ----
  2040. @SpringBootApplication
  2041. public class MyApplication {
  2042. @RestController
  2043. public static class MyController { <1>
  2044. @GetMapping
  2045. @AuthorizeReturnObject
  2046. Message getMessage() { <2>
  2047. return new Message(someUser, "hello!");
  2048. }
  2049. }
  2050. public static class Message { <3>
  2051. User to;
  2052. String text;
  2053. // ...
  2054. @AuthorizeReturnObject
  2055. public User getTo() { <4>
  2056. return this.to;
  2057. }
  2058. // ...
  2059. }
  2060. public static class User { <5>
  2061. // ...
  2062. }
  2063. public static void main(String[] args) {
  2064. SpringApplication.run(MyApplication.class);
  2065. }
  2066. }
  2067. ----
  2068. Kotlin::
  2069. +
  2070. [source,kotlin,role="secondary"]
  2071. ----
  2072. @SpringBootApplication
  2073. open class MyApplication {
  2074. @RestController
  2075. open class MyController { <1>
  2076. @GetMapping
  2077. @AuthorizeReturnObject
  2078. fun getMessage():Message { <2>
  2079. return Message(someUser, "hello!")
  2080. }
  2081. }
  2082. open class Message { <3>
  2083. val to: User
  2084. val test: String
  2085. // ...
  2086. @AuthorizeReturnObject
  2087. fun getTo(): User { <4>
  2088. return this.to
  2089. }
  2090. // ...
  2091. }
  2092. open class User { <5>
  2093. // ...
  2094. }
  2095. fun main(args: Array<String>) {
  2096. SpringApplication.run(MyApplication.class)
  2097. }
  2098. }
  2099. ----
  2100. ======
  2101. <1> - First, Spring Security finds the `MyController` bean
  2102. <2> - Finding a method that uses `@AuthorizeReturnObject`, it proxies `Message`, the return value, and registers that proxy class to `RuntimeHints`
  2103. <3> - Then, it traverses `Message` to see if it uses `@AuthorizeReturnObject`
  2104. <4> - Finding a method that uses `@AuthorizeReturnObject`, it proxies `User`, the return value, and registers that proxy class to `RuntimeHints`
  2105. <5> - Finally, it traverses `User` to see if it uses `@AuthorizeReturnObject`; finding nothing, the algorithm completes
  2106. There will be many times when Spring Security cannot determine the proxy class ahead of time since it may be hidden in an erased generic type.
  2107. Consider the following change to `MyController`:
  2108. [tabs]
  2109. ======
  2110. Java::
  2111. +
  2112. [source,java,role="primary"]
  2113. ----
  2114. @RestController
  2115. public static class MyController {
  2116. @GetMapping
  2117. @AuthorizeReturnObject
  2118. List<Message> getMessages() {
  2119. return List.of(new Message(someUser, "hello!"));
  2120. }
  2121. }
  2122. ----
  2123. Kotlin::
  2124. +
  2125. [source,kotlin,role="secondary"]
  2126. ----
  2127. @RestController
  2128. static class MyController {
  2129. @AuthorizeReturnObject
  2130. @GetMapping
  2131. fun getMessages(): Array<Message> = arrayOf(Message(someUser, "hello!"))
  2132. }
  2133. ----
  2134. ======
  2135. In this case, the generic type is erased and so it isn't apparent to Spring Security ahead-of-time that `Message` will need to be proxied at runtime.
  2136. To address this, you can publish `AuthorizeProxyFactoryHintsRegistrar` like so:
  2137. [tabs]
  2138. ======
  2139. Java::
  2140. +
  2141. [source,java,role="primary"]
  2142. ----
  2143. @Bean
  2144. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  2145. static SecurityHintsRegsitrar registerTheseToo(AuthorizationProxyFactory proxyFactory) {
  2146. return new AuthorizeReturnObjectHintsRegistrar(proxyFactory, Message.class);
  2147. }
  2148. ----
  2149. Kotlin::
  2150. +
  2151. [source,kotlin,role="secondary"]
  2152. ----
  2153. @Bean
  2154. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
  2155. fun registerTheseToo(proxyFactory: AuthorizationProxyFactory?): SecurityHintsRegistrar {
  2156. return AuthorizeReturnObjectHintsRegistrar(proxyFactory, Message::class.java)
  2157. }
  2158. ----
  2159. ======
  2160. Spring Security will register that class and then traverse its type as before.
  2161. [[fallback-values-authorization-denied]]
  2162. == Providing Fallback Values When Authorization is Denied
  2163. There are some scenarios where you may not wish to throw an `AuthorizationDeniedException` when a method is invoked without the required permissions.
  2164. Instead, you might wish to return a post-processed result, like a masked result, or a default value in cases where authorization denied happened before invoking the method.
  2165. Spring Security provides support for handling authorization denied on method invocation by using the javadoc:org.springframework.security.authorization.method.HandleAuthorizationDenied[format=annotation].
  2166. The handler works for denied authorizations that happened in the <<authorizing-with-annotations,`@PreAuthorize` and `@PostAuthorize` annotations>> as well as javadoc:org.springframework.security.authorization.AuthorizationDeniedException[] thrown from the method invocation itself.
  2167. Let's consider the example from the <<authorize-object,previous section>>, but instead of creating the `AccessDeniedExceptionInterceptor` to transform an `AccessDeniedException` to a `null` return value, we will use the `handlerClass` attribute from `@HandleAuthorizationDenied`:
  2168. [tabs]
  2169. ======
  2170. Java::
  2171. +
  2172. [source,java,role="primary"]
  2173. ----
  2174. public class NullMethodAuthorizationDeniedHandler implements MethodAuthorizationDeniedHandler { <1>
  2175. @Override
  2176. public Object handleDeniedInvocation(MethodInvocation methodInvocation, AuthorizationResult authorizationResult) {
  2177. return null;
  2178. }
  2179. }
  2180. @Configuration
  2181. @EnableMethodSecurity
  2182. public class SecurityConfig {
  2183. @Bean <2>
  2184. public NullMethodAuthorizationDeniedHandler nullMethodAuthorizationDeniedHandler() {
  2185. return new NullMethodAuthorizationDeniedHandler();
  2186. }
  2187. }
  2188. public class User {
  2189. // ...
  2190. @PreAuthorize(value = "hasAuthority('user:read')")
  2191. @HandleAuthorizationDenied(handlerClass = NullMethodAuthorizationDeniedHandler.class)
  2192. public String getEmail() {
  2193. return this.email;
  2194. }
  2195. }
  2196. ----
  2197. Kotlin::
  2198. +
  2199. [source,kotlin,role="secondary"]
  2200. ----
  2201. class NullMethodAuthorizationDeniedHandler : MethodAuthorizationDeniedHandler { <1>
  2202. override fun handleDeniedInvocation(methodInvocation: MethodInvocation, authorizationResult: AuthorizationResult): Any {
  2203. return null
  2204. }
  2205. }
  2206. @Configuration
  2207. @EnableMethodSecurity
  2208. class SecurityConfig {
  2209. @Bean <2>
  2210. fun nullMethodAuthorizationDeniedHandler(): NullMethodAuthorizationDeniedHandler {
  2211. return MaskMethodAuthorizationDeniedHandler()
  2212. }
  2213. }
  2214. class User (val name:String, @PreAuthorize(value = "hasAuthority('user:read')") @HandleAuthorizationDenied(handlerClass = NullMethodAuthorizationDeniedHandler::class) val email:String) <3>
  2215. ----
  2216. ======
  2217. <1> Create an implementation of `MethodAuthorizationDeniedHandler` that returns a `null` value
  2218. <2> Register the `NullMethodAuthorizationDeniedHandler` as a bean
  2219. <3> Annotate the method with `@HandleAuthorizationDenied` and pass the `NullMethodAuthorizationDeniedHandler` to the `handlerClass` attribute
  2220. And then you can verify that a `null` value is returned instead of the `AccessDeniedException`:
  2221. [TIP]
  2222. ====
  2223. You can also annotate your class with `@Component` instead of creating a `@Bean` method
  2224. ====
  2225. [tabs]
  2226. ======
  2227. Java::
  2228. +
  2229. [source,java,role="primary"]
  2230. ----
  2231. @Autowired
  2232. UserRepository users;
  2233. @Test
  2234. void getEmailWhenProxiedThenNullEmail() {
  2235. Optional<User> securedUser = users.findByName("name");
  2236. assertThat(securedUser.get().getEmail()).isNull();
  2237. }
  2238. ----
  2239. Kotlin::
  2240. +
  2241. [source,kotlin,role="secondary"]
  2242. ----
  2243. @Autowired
  2244. var users:UserRepository? = null
  2245. @Test
  2246. fun getEmailWhenProxiedThenNullEmail() {
  2247. val securedUser: Optional<User> = users.findByName("name")
  2248. assertThat(securedUser.get().getEmail()).isNull()
  2249. }
  2250. ----
  2251. ======
  2252. === Using the Denied Result From the Method Invocation
  2253. There are some scenarios where you might want to return a secure result derived from the denied result.
  2254. For example, if a user is not authorized to see email addresses, you might want to apply some masking on the original email address, i.e. _useremail@example.com_ would become _use\\******@example.com_.
  2255. For those scenarios, you can override the `handleDeniedInvocationResult` from the `MethodAuthorizationDeniedHandler`, which has the javadoc:org.springframework.security.authorization.method.MethodInvocationResult[] as an argument.
  2256. Let's continue with the previous example, but instead of returning `null`, we will return a masked value of the email:
  2257. [tabs]
  2258. ======
  2259. Java::
  2260. +
  2261. [source,java,role="primary"]
  2262. ----
  2263. public class EmailMaskingMethodAuthorizationDeniedHandler implements MethodAuthorizationDeniedHandler { <1>
  2264. @Override
  2265. public Object handleDeniedInvocation(MethodInvocation methodInvocation, AuthorizationResult authorizationResult) {
  2266. return "***";
  2267. }
  2268. @Override
  2269. public Object handleDeniedInvocationResult(MethodInvocationResult methodInvocationResult, AuthorizationResult authorizationResult) {
  2270. String email = (String) methodInvocationResult.getResult();
  2271. return email.replaceAll("(^[^@]{3}|(?!^)\\G)[^@]", "$1*");
  2272. }
  2273. }
  2274. @Configuration
  2275. @EnableMethodSecurity
  2276. public class SecurityConfig {
  2277. @Bean <2>
  2278. public EmailMaskingMethodAuthorizationDeniedHandler emailMaskingMethodAuthorizationDeniedHandler() {
  2279. return new EmailMaskingMethodAuthorizationDeniedHandler();
  2280. }
  2281. }
  2282. public class User {
  2283. // ...
  2284. @PostAuthorize(value = "hasAuthority('user:read')")
  2285. @HandleAuthorizationDenied(handlerClass = EmailMaskingMethodAuthorizationDeniedHandler.class)
  2286. public String getEmail() {
  2287. return this.email;
  2288. }
  2289. }
  2290. ----
  2291. Kotlin::
  2292. +
  2293. [source,kotlin,role="secondary"]
  2294. ----
  2295. class EmailMaskingMethodAuthorizationDeniedHandler : MethodAuthorizationDeniedHandler {
  2296. override fun handleDeniedInvocation(methodInvocation: MethodInvocation, authorizationResult: AuthorizationResult): Any {
  2297. return "***"
  2298. }
  2299. override fun handleDeniedInvocationResult(methodInvocationResult: MethodInvocationResult, authorizationResult: AuthorizationResult): Any {
  2300. val email = methodInvocationResult.result as String
  2301. return email.replace("(^[^@]{3}|(?!^)\\G)[^@]".toRegex(), "$1*")
  2302. }
  2303. }
  2304. @Configuration
  2305. @EnableMethodSecurity
  2306. class SecurityConfig {
  2307. @Bean
  2308. fun emailMaskingMethodAuthorizationDeniedHandler(): EmailMaskingMethodAuthorizationDeniedHandler {
  2309. return EmailMaskingMethodAuthorizationDeniedHandler()
  2310. }
  2311. }
  2312. class User (val name:String, @PostAuthorize(value = "hasAuthority('user:read')") @HandleAuthorizationDenied(handlerClass = EmailMaskingMethodAuthorizationDeniedHandler::class) val email:String) <3>
  2313. ----
  2314. ======
  2315. <1> Create an implementation of `MethodAuthorizationDeniedHandler` that returns a masked value of the unauthorized result value
  2316. <2> Register the `EmailMaskingMethodAuthorizationDeniedHandler` as a bean
  2317. <3> Annotate the method with `@HandleAuthorizationDenied` and pass the `EmailMaskingMethodAuthorizationDeniedHandler` to the `handlerClass` attribute
  2318. And then you can verify that a masked email is returned instead of an `AccessDeniedException`:
  2319. [WARNING]
  2320. ====
  2321. Since you have access to the original denied value, make sure that you correctly handle it and do not return it to the caller.
  2322. ====
  2323. [tabs]
  2324. ======
  2325. Java::
  2326. +
  2327. [source,java,role="primary"]
  2328. ----
  2329. @Autowired
  2330. UserRepository users;
  2331. @Test
  2332. void getEmailWhenProxiedThenMaskedEmail() {
  2333. Optional<User> securedUser = users.findByName("name");
  2334. // email is useremail@example.com
  2335. assertThat(securedUser.get().getEmail()).isEqualTo("use******@example.com");
  2336. }
  2337. ----
  2338. Kotlin::
  2339. +
  2340. [source,kotlin,role="secondary"]
  2341. ----
  2342. @Autowired
  2343. var users:UserRepository? = null
  2344. @Test
  2345. fun getEmailWhenProxiedThenMaskedEmail() {
  2346. val securedUser: Optional<User> = users.findByName("name")
  2347. // email is useremail@example.com
  2348. assertThat(securedUser.get().getEmail()).isEqualTo("use******@example.com")
  2349. }
  2350. ----
  2351. ======
  2352. When implementing the `MethodAuthorizationDeniedHandler` you have a few options on what type you can return:
  2353. - A `null` value.
  2354. - A non-null value, respecting the method's return type.
  2355. - Throw an exception, usually an instance of `AuthorizationDeniedException`. This is the default behavior.
  2356. - A `Mono` type for reactive applications.
  2357. Note that since the handler must be registered as beans in your application context, you can inject dependencies into them if you need a more complex logic.
  2358. In addition to that, you have available the `MethodInvocation` or the `MethodInvocationResult`, as well as the `AuthorizationResult` for more details related to the authorization decision.
  2359. [[deciding-return-based-parameters]]
  2360. === Deciding What to Return Based on Available Parameters
  2361. Consider a scenario where there might be multiple mask values for different methods, it would be not so productive if we had to create a handler for each of those methods, although it is perfectly fine to do that.
  2362. In such cases, we can use the information passed via parameters to decide what to do.
  2363. For example, we can create a custom `@Mask` annotation and a handler that detects that annotation to decide what mask value to return:
  2364. [tabs]
  2365. ======
  2366. Java::
  2367. +
  2368. [source,java,role="primary"]
  2369. ----
  2370. import org.springframework.core.annotation.AnnotationUtils;
  2371. @Target({ ElementType.METHOD, ElementType.TYPE })
  2372. @Retention(RetentionPolicy.RUNTIME)
  2373. public @interface Mask {
  2374. String value();
  2375. }
  2376. public class MaskAnnotationDeniedHandler implements MethodAuthorizationDeniedHandler {
  2377. @Override
  2378. public Object handleDeniedInvocation(MethodInvocation methodInvocation, AuthorizationResult authorizationResult) {
  2379. Mask mask = AnnotationUtils.getAnnotation(methodInvocation.getMethod(), Mask.class);
  2380. return mask.value();
  2381. }
  2382. }
  2383. @Configuration
  2384. @EnableMethodSecurity
  2385. public class SecurityConfig {
  2386. @Bean
  2387. public MaskAnnotationDeniedHandler maskAnnotationDeniedHandler() {
  2388. return new MaskAnnotationDeniedHandler();
  2389. }
  2390. }
  2391. @Component
  2392. public class MyService {
  2393. @PreAuthorize(value = "hasAuthority('user:read')")
  2394. @HandleAuthorizationDenied(handlerClass = MaskAnnotationDeniedHandler.class)
  2395. @Mask("***")
  2396. public String foo() {
  2397. return "foo";
  2398. }
  2399. @PreAuthorize(value = "hasAuthority('user:read')")
  2400. @HandleAuthorizationDenied(handlerClass = MaskAnnotationDeniedHandler.class)
  2401. @Mask("???")
  2402. public String bar() {
  2403. return "bar";
  2404. }
  2405. }
  2406. ----
  2407. Kotlin::
  2408. +
  2409. [source,kotlin,role="secondary"]
  2410. ----
  2411. import org.springframework.core.annotation.AnnotationUtils
  2412. @Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
  2413. @Retention(AnnotationRetention.RUNTIME)
  2414. annotation class Mask(val value: String)
  2415. class MaskAnnotationDeniedHandler : MethodAuthorizationDeniedHandler {
  2416. override fun handleDeniedInvocation(methodInvocation: MethodInvocation, authorizationResult: AuthorizationResult): Any {
  2417. val mask = AnnotationUtils.getAnnotation(methodInvocation.method, Mask::class.java)
  2418. return mask.value
  2419. }
  2420. }
  2421. @Configuration
  2422. @EnableMethodSecurity
  2423. class SecurityConfig {
  2424. @Bean
  2425. fun maskAnnotationDeniedHandler(): MaskAnnotationDeniedHandler {
  2426. return MaskAnnotationDeniedHandler()
  2427. }
  2428. }
  2429. @Component
  2430. class MyService {
  2431. @PreAuthorize(value = "hasAuthority('user:read')")
  2432. @HandleAuthorizationDenied(handlerClass = MaskAnnotationDeniedHandler::class)
  2433. @Mask("***")
  2434. fun foo(): String {
  2435. return "foo"
  2436. }
  2437. @PreAuthorize(value = "hasAuthority('user:read')")
  2438. @HandleAuthorizationDenied(handlerClass = MaskAnnotationDeniedHandler::class)
  2439. @Mask("???")
  2440. fun bar(): String {
  2441. return "bar"
  2442. }
  2443. }
  2444. ----
  2445. ======
  2446. Now the return values when access is denied will be decided based on the `@Mask` annotation:
  2447. [tabs]
  2448. ======
  2449. Java::
  2450. +
  2451. [source,java,role="primary"]
  2452. ----
  2453. @Autowired
  2454. MyService myService;
  2455. @Test
  2456. void fooWhenDeniedThenReturnStars() {
  2457. String value = this.myService.foo();
  2458. assertThat(value).isEqualTo("***");
  2459. }
  2460. @Test
  2461. void barWhenDeniedThenReturnQuestionMarks() {
  2462. String value = this.myService.foo();
  2463. assertThat(value).isEqualTo("???");
  2464. }
  2465. ----
  2466. Kotlin::
  2467. +
  2468. [source,kotlin,role="secondary"]
  2469. ----
  2470. @Autowired
  2471. var myService: MyService
  2472. @Test
  2473. fun fooWhenDeniedThenReturnStars() {
  2474. val value: String = myService.foo()
  2475. assertThat(value).isEqualTo("***")
  2476. }
  2477. @Test
  2478. fun barWhenDeniedThenReturnQuestionMarks() {
  2479. val value: String = myService.foo()
  2480. assertThat(value).isEqualTo("???")
  2481. }
  2482. ----
  2483. ======
  2484. === Combining with Meta Annotation Support
  2485. You can also combine the `@HandleAuthorizationDenied` with other annotations in order to reduce and simplify the annotations in a method.
  2486. Let's consider the <<deciding-return-based-parameters,example from the previous section>> and merge `@HandleAuthorizationDenied` with `@Mask`:
  2487. [tabs]
  2488. ======
  2489. Java::
  2490. +
  2491. [source,java,role="primary"]
  2492. ----
  2493. @Target({ ElementType.METHOD, ElementType.TYPE })
  2494. @Retention(RetentionPolicy.RUNTIME)
  2495. @HandleAuthorizationDenied(handlerClass = MaskAnnotationDeniedHandler.class)
  2496. public @interface Mask {
  2497. String value();
  2498. }
  2499. @Mask("***")
  2500. public String myMethod() {
  2501. // ...
  2502. }
  2503. ----
  2504. Kotlin::
  2505. +
  2506. [source,kotlin,role="secondary"]
  2507. ----
  2508. @Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
  2509. @Retention(AnnotationRetention.RUNTIME)
  2510. @HandleAuthorizationDenied(handlerClass = MaskAnnotationDeniedHandler::class)
  2511. annotation class Mask(val value: String)
  2512. @Mask("***")
  2513. fun myMethod(): String {
  2514. // ...
  2515. }
  2516. ----
  2517. ======
  2518. Now you do not have to remember to add both annotations when you need a mask behavior in your method.
  2519. Make sure to read the <<meta-annotations,Meta Annotations Support>> section for more details on the usage.
  2520. [[migration-enableglobalmethodsecurity]]
  2521. == Migrating from `@EnableGlobalMethodSecurity`
  2522. If you are using `@EnableGlobalMethodSecurity`, you should migrate to `@EnableMethodSecurity`.
  2523. [[servlet-replace-globalmethodsecurity-with-methodsecurity]]
  2524. === 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]
  2525. javadoc:org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity[format=annotation] and xref:servlet/appendix/namespace/method-security.adoc#nsa-global-method-security[`<global-method-security>`] are deprecated in favor of javadoc:org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity[`@EnableMethodSecurity`] and xref:servlet/appendix/namespace/method-security.adoc#nsa-method-security[`<method-security>`], respectively.
  2526. 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.
  2527. This means that the following two listings are functionally equivalent:
  2528. [tabs]
  2529. ======
  2530. Java::
  2531. +
  2532. [source,java,role="primary"]
  2533. ----
  2534. @EnableGlobalMethodSecurity(prePostEnabled = true)
  2535. ----
  2536. Kotlin::
  2537. +
  2538. [source,kotlin,role="secondary"]
  2539. ----
  2540. @EnableGlobalMethodSecurity(prePostEnabled = true)
  2541. ----
  2542. Xml::
  2543. +
  2544. [source,xml,role="secondary"]
  2545. ----
  2546. <global-method-security pre-post-enabled="true"/>
  2547. ----
  2548. ======
  2549. and:
  2550. [tabs]
  2551. ======
  2552. Java::
  2553. +
  2554. [source,java,role="primary"]
  2555. ----
  2556. @EnableMethodSecurity
  2557. ----
  2558. Kotlin::
  2559. +
  2560. [source,kotlin,role="secondary"]
  2561. ----
  2562. @EnableMethodSecurity
  2563. ----
  2564. Xml::
  2565. +
  2566. [source,xml,role="secondary"]
  2567. ----
  2568. <method-security/>
  2569. ----
  2570. ======
  2571. For applications not using the pre-post annotations, make sure to turn it off to avoid activating unwanted behavior.
  2572. For example, a listing like:
  2573. [tabs]
  2574. ======
  2575. Java::
  2576. +
  2577. [source,java,role="primary"]
  2578. ----
  2579. @EnableGlobalMethodSecurity(securedEnabled = true)
  2580. ----
  2581. Kotlin::
  2582. +
  2583. [source,kotlin,role="secondary"]
  2584. ----
  2585. @EnableGlobalMethodSecurity(securedEnabled = true)
  2586. ----
  2587. Xml::
  2588. +
  2589. [source,xml,role="secondary"]
  2590. ----
  2591. <global-method-security secured-enabled="true"/>
  2592. ----
  2593. ======
  2594. should change to:
  2595. [tabs]
  2596. ======
  2597. Java::
  2598. +
  2599. [source,java,role="primary"]
  2600. ----
  2601. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  2602. ----
  2603. Kotlin::
  2604. +
  2605. [source,kotlin,role="secondary"]
  2606. ----
  2607. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  2608. ----
  2609. Xml::
  2610. +
  2611. [source,xml,role="secondary"]
  2612. ----
  2613. <method-security secured-enabled="true" pre-post-enabled="false"/>
  2614. ----
  2615. ======
  2616. === Use a Custom `@Bean` instead of subclassing `DefaultMethodSecurityExpressionHandler`
  2617. As a performance optimization, a new method was introduced to `MethodSecurityExpressionHandler` that takes a `Supplier<Authentication>` instead of an `Authentication`.
  2618. This allows Spring Security to defer the lookup of the `Authentication`, and is taken advantage of automatically when you use `@EnableMethodSecurity` instead of `@EnableGlobalMethodSecurity`.
  2619. However, let's say that your code extends `DefaultMethodSecurityExpressionHandler` and overrides `createSecurityExpressionRoot(Authentication, MethodInvocation)` to return a custom `SecurityExpressionRoot` instance.
  2620. This will no longer work because the arrangement that `@EnableMethodSecurity` sets up calls `createEvaluationContext(Supplier<Authentication>, MethodInvocation)` instead.
  2621. Happily, such a level of customization is often unnecessary.
  2622. Instead, you can create a custom bean with the authorization methods that you need.
  2623. For example, let's say you are wanting a custom evaluation of `@PostAuthorize("hasAuthority('ADMIN')")`.
  2624. You can create a custom `@Bean` like this one:
  2625. [tabs]
  2626. ======
  2627. Java::
  2628. +
  2629. [source,java,role="primary"]
  2630. ----
  2631. class MyAuthorizer {
  2632. boolean isAdmin(MethodSecurityExpressionOperations root) {
  2633. boolean decision = root.hasAuthority("ADMIN");
  2634. // custom work ...
  2635. return decision;
  2636. }
  2637. }
  2638. ----
  2639. Kotlin::
  2640. +
  2641. [source,kotlin,role="secondary"]
  2642. ----
  2643. class MyAuthorizer {
  2644. fun isAdmin(val root: MethodSecurityExpressionOperations): boolean {
  2645. val decision = root.hasAuthority("ADMIN");
  2646. // custom work ...
  2647. return decision;
  2648. }
  2649. }
  2650. ----
  2651. ======
  2652. and then refer to it in the annotation like so:
  2653. [tabs]
  2654. ======
  2655. Java::
  2656. +
  2657. [source,java,role="primary"]
  2658. ----
  2659. @PreAuthorize("@authz.isAdmin(#root)")
  2660. ----
  2661. Kotlin::
  2662. +
  2663. [source,kotlin,role="secondary"]
  2664. ----
  2665. @PreAuthorize("@authz.isAdmin(#root)")
  2666. ----
  2667. ======
  2668. [[subclass-defaultmethodsecurityexpressionhandler]]
  2669. ==== I'd still prefer to subclass `DefaultMethodSecurityExpressionHandler`
  2670. If you must continue subclassing `DefaultMethodSecurityExpressionHandler`, you can still do so.
  2671. Instead, override the `createEvaluationContext(Supplier<Authentication>, MethodInvocation)` method like so:
  2672. [tabs]
  2673. ======
  2674. Java::
  2675. +
  2676. [source,java,role="primary"]
  2677. ----
  2678. @Component
  2679. class MyExpressionHandler extends DefaultMethodSecurityExpressionHandler {
  2680. @Override
  2681. public EvaluationContext createEvaluationContext(Supplier<Authentication> authentication, MethodInvocation mi) {
  2682. StandardEvaluationContext context = (StandardEvaluationContext) super.createEvaluationContext(authentication, mi);
  2683. MethodSecurityExpressionOperations delegate = (MethodSecurityExpressionOperations) context.getRootObject().getValue();
  2684. MySecurityExpressionRoot root = new MySecurityExpressionRoot(delegate);
  2685. context.setRootObject(root);
  2686. return context;
  2687. }
  2688. }
  2689. ----
  2690. Kotlin::
  2691. +
  2692. [source,kotlin,role="secondary"]
  2693. ----
  2694. @Component
  2695. class MyExpressionHandler: DefaultMethodSecurityExpressionHandler {
  2696. override fun createEvaluationContext(val authentication: Supplier<Authentication>,
  2697. val mi: MethodInvocation): EvaluationContext {
  2698. val context = super.createEvaluationContext(authentication, mi) as StandardEvaluationContext
  2699. val delegate = context.getRootObject().getValue() as MethodSecurityExpressionOperations
  2700. val root = MySecurityExpressionRoot(delegate)
  2701. context.setRootObject(root)
  2702. return context
  2703. }
  2704. }
  2705. ----
  2706. ======
  2707. == Further Reading
  2708. 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.
  2709. 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].