method-security.adoc 96 KB

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