method-security.adoc 88 KB

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