method-security.adoc 87 KB

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