method-security.adoc 88 KB

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