method-security.adoc 96 KB

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