method-security.adoc 88 KB

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