method-security.adoc 96 KB

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