authorization.adoc 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985
  1. = Authorization Migrations
  2. The following steps relate to changes around how authorization is performed.
  3. == Use `AuthorizationManager` for Method Security
  4. xref:servlet/authorization/method-security.adoc[Method Security] has been xref:servlet/authorization/method-security.adoc#jc-enable-method-security[simplified] through {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[the `AuthorizationManager` API] and direct use of Spring AOP.
  5. Should you run into trouble with making these changes, note that `@EnableGlobalMethodSecurity`, while deprecated, will not be removed in 6.0, allowing you to opt out by sticking with the old annotation.
  6. [[servlet-replace-globalmethodsecurity-with-methodsecurity]]
  7. === 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]
  8. {security-api-url}org/springframework/security/config/annotation/method/configuration/EnableGlobalMethodSecurity.html[`@EnableGlobalMethodSecurity`] and xref:servlet/appendix/namespace/method-security.adoc#nsa-global-method-security[`<global-method-security>`] are deprecated in favor of {security-api-url}org/springframework/security/config/annotation/method/configuration/EnableMethodSecurity.html[`@EnableMethodSecurity`] and xref:servlet/appendix/namespace/method-security.adoc#nsa-method-security[`<method-security>`], respectively.
  9. 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.
  10. This means that the following two listings are functionally equivalent:
  11. [tabs]
  12. ======
  13. Java::
  14. +
  15. [source,java,role="primary"]
  16. ----
  17. @EnableGlobalMethodSecurity(prePostEnabled = true)
  18. ----
  19. Kotlin::
  20. +
  21. [source,kotlin,role="secondary"]
  22. ----
  23. @EnableGlobalMethodSecurity(prePostEnabled = true)
  24. ----
  25. Xml::
  26. +
  27. [source,xml,role="secondary"]
  28. ----
  29. <global-method-security pre-post-enabled="true"/>
  30. ----
  31. ======
  32. and:
  33. [tabs]
  34. ======
  35. Java::
  36. +
  37. [source,java,role="primary"]
  38. ----
  39. @EnableMethodSecurity
  40. ----
  41. Kotlin::
  42. +
  43. [source,kotlin,role="secondary"]
  44. ----
  45. @EnableMethodSecurity
  46. ----
  47. Xml::
  48. +
  49. [source,xml,role="secondary"]
  50. ----
  51. <method-security/>
  52. ----
  53. ======
  54. For applications not using the pre-post annotations, make sure to turn it off to avoid activating unwanted behavior.
  55. For example, a listing like:
  56. [tabs]
  57. ======
  58. Java::
  59. +
  60. [source,java,role="primary"]
  61. ----
  62. @EnableGlobalMethodSecurity(securedEnabled = true)
  63. ----
  64. Kotlin::
  65. +
  66. [source,kotlin,role="secondary"]
  67. ----
  68. @EnableGlobalMethodSecurity(securedEnabled = true)
  69. ----
  70. Xml::
  71. +
  72. [source,xml,role="secondary"]
  73. ----
  74. <global-method-security secured-enabled="true"/>
  75. ----
  76. ======
  77. should change to:
  78. [tabs]
  79. ======
  80. Java::
  81. +
  82. [source,java,role="primary"]
  83. ----
  84. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  85. ----
  86. Kotlin::
  87. +
  88. [source,kotlin,role="secondary"]
  89. ----
  90. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  91. ----
  92. Xml::
  93. +
  94. [source,xml,role="secondary"]
  95. ----
  96. <method-security secured-enabled="true" pre-post-enabled="false"/>
  97. ----
  98. ======
  99. === Change the `order` value in `@EnableTransactionManagement`
  100. `@EnableTransactionManagement` and `@EnableGlobalMethodSecurity` have the same `order` value, `Integer.MAX_VALUE`.
  101. This means that their order in the Spring AOP Advisor chain relative to each other is undefined.
  102. This is often fine since most method security expressions don't require an open transaction to function correctly; however, historically it was sometimes necessary to ensure one happens before the other by setting their `order` values.
  103. `@EnableMethodSecurity` does not have an `order` value since it publishes multiple interceptors.
  104. Indeed, it cannot attempt backward-compatibility with `@EnableTransactionManagement` since it cannot set all the interceptors to be in the same advisor chain location.
  105. Instead, the values for the `@EnableMethodSecurity` interceptors are based off of an offset of 0.
  106. The `@PreFilter` interceptor has an order of 100; `@PostAuthorize`, 200; and so on.
  107. So, if after updating you find that your method security expressions are not working due to not having an open transaction, please change your transaction annotation definition from the following:
  108. [tabs]
  109. ======
  110. Java::
  111. +
  112. [source,java,role="primary"]
  113. ----
  114. @EnableTransactionManagement
  115. ----
  116. Kotlin::
  117. +
  118. [source,kotlin,role="secondary"]
  119. ----
  120. @EnableTransactionManagement
  121. ----
  122. Xml::
  123. +
  124. [source,xml,role="secondary"]
  125. ----
  126. <tx:annotation-driven ref="txManager"/>
  127. ----
  128. ======
  129. to:
  130. [tabs]
  131. ======
  132. Java::
  133. +
  134. [source,java,role="primary"]
  135. ----
  136. @EnableTransactionManagement(order = 0)
  137. ----
  138. Kotlin::
  139. +
  140. [source,kotlin,role="secondary"]
  141. ----
  142. @EnableTransactionManagement(order = 0)
  143. ----
  144. Xml::
  145. +
  146. [source,xml,role="secondary"]
  147. ----
  148. <tx:annotation-driven ref="txManager" order="0"/>
  149. ----
  150. ======
  151. In this way, the transaction AOP advice will be placed before Spring Security's advice and the transaction will be open when your authorization SpEL expressions are evaluated.
  152. === Use a Custom `@Bean` instead of subclassing `DefaultMethodSecurityExpressionHandler`
  153. As a performance optimization, a new method was introduced to `MethodSecurityExpressionHandler` that takes a `Supplier<Authentication>` instead of an `Authentication`.
  154. This allows Spring Security to defer the lookup of the `Authentication`, and is taken advantage of automatically when you use `@EnableMethodSecurity` instead of `@EnableGlobalMethodSecurity`.
  155. However, let's say that your code extends `DefaultMethodSecurityExpressionHandler` and overrides `createSecurityExpressionRoot(Authentication, MethodInvocation)` to return a custom `SecurityExpressionRoot` instance.
  156. This will no longer work because the arrangement that `@EnableMethodSecurity` sets up calls `createEvaluationContext(Supplier<Authentication>, MethodInvocation)` instead.
  157. Happily, such a level of customization is often unnecessary.
  158. Instead, you can create a custom bean with the authorization methods that you need.
  159. For example, let's say you are wanting a custom evaluation of `@PostAuthorize("hasAuthority('ADMIN')")`.
  160. You can create a custom `@Bean` like this one:
  161. [tabs]
  162. ======
  163. Java::
  164. +
  165. [source,java,role="primary"]
  166. ----
  167. class MyAuthorizer {
  168. boolean isAdmin(MethodSecurityExpressionOperations root) {
  169. boolean decision = root.hasAuthority("ADMIN");
  170. // custom work ...
  171. return decision;
  172. }
  173. }
  174. ----
  175. Kotlin::
  176. +
  177. [source,kotlin,role="secondary"]
  178. ----
  179. class MyAuthorizer {
  180. fun isAdmin(val root: MethodSecurityExpressionOperations): boolean {
  181. val decision = root.hasAuthority("ADMIN");
  182. // custom work ...
  183. return decision;
  184. }
  185. }
  186. ----
  187. ======
  188. and then refer to it in the annotation like so:
  189. [tabs]
  190. ======
  191. Java::
  192. +
  193. [source,java,role="primary"]
  194. ----
  195. @PreAuthorize("@authz.isAdmin(#root)")
  196. ----
  197. Kotlin::
  198. +
  199. [source,kotlin,role="secondary"]
  200. ----
  201. @PreAuthorize("@authz.isAdmin(#root)")
  202. ----
  203. ======
  204. ==== I'd still prefer to subclass `DefaultMethodSecurityExpressionHandler`
  205. If you must continue subclassing `DefaultMethodSecurityExpressionHandler`, you can still do so.
  206. Instead, override the `createEvaluationContext(Supplier<Authentication>, MethodInvocation)` method like so:
  207. [tabs]
  208. ======
  209. Java::
  210. +
  211. [source,java,role="primary"]
  212. ----
  213. @Component
  214. class MyExpressionHandler extends DefaultMethodSecurityExpressionHandler {
  215. @Override
  216. public EvaluationContext createEvaluationContext(
  217. Supplier<Authentication> authentication, MethodInvocation mi) {
  218. StandardEvaluationContext context = (StandardEvaluationContext) super.createEvaluationContext(authentication, mi);
  219. MySecurityExpressionRoot root = new MySecurityExpressionRoot(authentication, invocation);
  220. root.setPermissionEvaluator(getPermissionEvaluator());
  221. root.setTrustResolver(new AuthenticationTrustResolverImpl());
  222. root.setRoleHierarchy(getRoleHierarchy());
  223. context.setRootObject(root);
  224. return context;
  225. }
  226. }
  227. ----
  228. Kotlin::
  229. +
  230. [source,kotlin,role="secondary"]
  231. ----
  232. @Component
  233. class MyExpressionHandler: DefaultMethodSecurityExpressionHandler {
  234. override fun createEvaluationContext(val authentication: Supplier<Authentication>,
  235. val mi: MethodInvocation): EvaluationContext {
  236. val context = super.createEvaluationContext(authentication, mi) as StandardEvaluationContext;
  237. val root = new MySecurityExpressionRoot(authentication, invocation);
  238. root.setPermissionEvaluator(getPermissionEvaluator());
  239. root.setTrustResolver(new AuthenticationTrustResolverImpl());
  240. root.setRoleHierarchy(getRoleHierarchy());
  241. context.setRootObject(root);
  242. return context;
  243. }
  244. }
  245. ----
  246. ======
  247. ==== Opt-out Steps
  248. If you need to opt-out of these changes, you can use `@EnableGlobalMethodSecurity` instead of `@EnableMethodSecurity`
  249. [[servlet-replace-permissionevaluator-bean-with-methodsecurityexpression-handler]]
  250. === Publish a `MethodSecurityExpressionHandler` instead of a `PermissionEvaluator`
  251. `@EnableMethodSecurity` does not pick up a `PermissionEvaluator`.
  252. This helps keep its API simple.
  253. If you have a custom {security-api-url}org/springframework/security/access/PermissionEvaluator.html[`PermissionEvaluator`] `@Bean`, please change it from:
  254. [tabs]
  255. ======
  256. Java::
  257. +
  258. [source,java,role="primary"]
  259. ----
  260. @Bean
  261. static PermissionEvaluator permissionEvaluator() {
  262. // ... your evaluator
  263. }
  264. ----
  265. Kotlin::
  266. +
  267. [source,kotlin,role="secondary"]
  268. ----
  269. companion object {
  270. @Bean
  271. fun permissionEvaluator(): PermissionEvaluator {
  272. // ... your evaluator
  273. }
  274. }
  275. ----
  276. ======
  277. to:
  278. [tabs]
  279. ======
  280. Java::
  281. +
  282. [source,java,role="primary"]
  283. ----
  284. @Bean
  285. static MethodSecurityExpressionHandler expressionHandler() {
  286. var expressionHandler = new DefaultMethodSecurityExpressionHandler();
  287. expressionHandler.setPermissionEvaluator(myPermissionEvaluator);
  288. return expressionHandler;
  289. }
  290. ----
  291. Kotlin::
  292. +
  293. [source,kotlin,role="secondary"]
  294. ----
  295. companion object {
  296. @Bean
  297. fun expressionHandler(): MethodSecurityExpressionHandler {
  298. val expressionHandler = DefaultMethodSecurityExpressionHandler
  299. expressionHandler.setPermissionEvaluator(myPermissionEvaluator)
  300. return expressionHandler
  301. }
  302. }
  303. ----
  304. ======
  305. === Replace any custom method-security ``AccessDecisionManager``s
  306. Your application may have a custom {security-api-url}org/springframework/security/access/AccessDecisionManager.html[`AccessDecisionManager`] or {security-api-url}org/springframework/security/access/AccessDecisionVoter.html[`AccessDecisionVoter`] arrangement.
  307. The preparation strategy will depend on your reason for each arrangement.
  308. Read on to find the best match for your situation.
  309. ==== I use `UnanimousBased`
  310. If your application uses {security-api-url}org/springframework/security/access/vote/UnanimousBased.html[`UnanimousBased`] with the default voters, you likely need do nothing since unanimous-based is the default behavior with {security-api-url}org/springframework/security/config/annotation/method/configuration/EnableMethodSecurity.html[`@EnableMethodSecurity`].
  311. However, if you do discover that you cannot accept the default authorization managers, you can use `AuthorizationManagers.allOf` to compose your own arrangement.
  312. Note that there is a difference with `allOf`, which is that if all delegates abstain then it grants authorization.
  313. If you must deny authorization when all delegates abstain, please implement a composite {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] that takes the set of delegate ``AuthorizationManager``s into account.
  314. Having done that, please follow the details in the reference manual for xref:servlet/authorization/method-security.adoc#jc-method-security-custom-authorization-manager[adding a custom `AuthorizationManager`].
  315. ==== I use `AffirmativeBased`
  316. If your application uses {security-api-url}org/springframework/security/access/vote/AffirmativeBased.html[`AffirmativeBased`], then you can construct an equivalent {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`], like so:
  317. [tabs]
  318. ======
  319. Java::
  320. +
  321. [source,java,role="primary"]
  322. ----
  323. AuthorizationManager<MethodInvocation> authorization = AuthorizationManagers.anyOf(
  324. // ... your list of authorization managers
  325. )
  326. ----
  327. Kotlin::
  328. +
  329. [source,kotlin,role="secondary"]
  330. ----
  331. val authorization = AuthorizationManagers.anyOf(
  332. // ... your list of authorization managers
  333. )
  334. ----
  335. ======
  336. Once you have implemented `AuthorizationManager`, please follow the details in the reference manual for xref:servlet/authorization/method-security.adoc#jc-method-security-custom-authorization-manager[adding a custom `AuthorizationManager`].
  337. ==== I use `ConsensusBased`
  338. There is no framework-provided equivalent for {security-api-url}org/springframework/security/access/vote/ConsensusBased.html[`ConsensusBased`].
  339. In that case, please implement a composite {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] that takes the set of delegate ``AuthorizationManager``s into account.
  340. Once you have implemented `AuthorizationManager`, please follow the details in the reference manual for xref:servlet/authorization/method-security.adoc#jc-method-security-custom-authorization-manager[adding a custom `AuthorizationManager`].
  341. ==== I use a custom `AccessDecisionVoter`
  342. You should either change the class to implement {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] or create an adapter.
  343. Without knowing what your custom voter is doing, it is impossible to recommend a general-purpose solution.
  344. By way of example, though, here is what adapting {security-api-url}org/springframework/security/access/SecurityMetadataSource.html[`SecurityMetadataSource`] and {security-api-url}org/springframework/security/access/AccessDecisionVoter.html[`AccessDecisionVoter`] for `@PreAuthorize` would look like:
  345. [tabs]
  346. ======
  347. Java::
  348. +
  349. [source,java,role="primary"]
  350. ----
  351. public final class PreAuthorizeAuthorizationManagerAdapter implements AuthorizationManager<MethodInvocation> {
  352. private final SecurityMetadataSource metadata;
  353. private final AccessDecisionVoter voter;
  354. public PreAuthorizeAuthorizationManagerAdapter(MethodSecurityExpressionHandler expressionHandler) {
  355. ExpressionBasedAnnotationAttributeFactory attributeFactory =
  356. new ExpressionBasedAnnotationAttributeFactory(expressionHandler);
  357. this.metadata = new PrePostAnnotationSecurityMetadataSource(attributeFactory);
  358. ExpressionBasedPreInvocationAdvice expressionAdvice = new ExpressionBasedPreInvocationAdvice();
  359. expressionAdvice.setExpressionHandler(expressionHandler);
  360. this.voter = new PreInvocationAuthorizationAdviceVoter(expressionAdvice);
  361. }
  362. public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocation invocation) {
  363. List<ConfigAttribute> attributes = this.metadata.getAttributes(invocation, AopUtils.getTargetClass(invocation.getThis()));
  364. int decision = this.voter.vote(authentication.get(), invocation, attributes);
  365. if (decision == ACCESS_GRANTED) {
  366. return new AuthorizationDecision(true);
  367. }
  368. if (decision == ACCESS_DENIED) {
  369. return new AuthorizationDecision(false);
  370. }
  371. return null; // abstain
  372. }
  373. }
  374. ----
  375. ======
  376. Once you have implemented `AuthorizationManager`, please follow the details in the reference manual for xref:servlet/authorization/method-security.adoc#jc-method-security-custom-authorization-manager[adding a custom `AuthorizationManager`].
  377. ==== I use `AfterInvocationManager` or `AfterInvocationProvider`
  378. {security-api-url}org/springframework/security/access/intercept/AfterInvocationManager.html;[`AfterInvocationManager`] and {security-api-url}org/springframework/security/access/intercept/AfterInvocationProvider.html[`AfterInvocationProvider`] make an authorization decision about an invocation's result.
  379. For example, in the case of method invocation, these make an authorization decision about a method's return value.
  380. In Spring Security 3.0, authorization decision-making was standardized into the xref:servlet/authorization/method-security.adoc[`@PostAuthorize` and `@PostFilter` annotations].
  381. `@PostAuthorize` is for deciding whether the return value as a whole was permitted to be returned.
  382. `@PostFilter` is for filtering individual entries from a returned collection, array, or stream.
  383. These two annotations should serve most needs, and you are encouraged to migrate to one or both of them since `AfterInvocationProvider` and `AfterInvocationManager` are now deprecated.
  384. If you've implemented your own `AfterInvocationManager` or `AfterInvocationProvider`, you should first ask yourself what it is trying to do.
  385. If it is trying to authorize the return type, <<_i_use_a_custom_accessdecisionvoter,consider implementing `AuthorizationManager<MethodInvocationResult>` and using `AfterMethodAuthorizationManagerInterceptor`>>. Or publishing a custom bean and using `@PostAuthorize("@myBean.authorize(#root)")`.
  386. If it is trying to filter, then consider publishing a custom bean and using `@PostFilter("@mybean.authorize(#root)")`.
  387. Or, if needed, you can implement your own `MethodInterceptor`, taking a look at `PostFilterAuthorizationMethodInterceptor` and `PrePostMethodSecurityConfiguration` for an example.
  388. ==== I use `RunAsManager`
  389. There is currently https://github.com/spring-projects/spring-security/issues/11331[no replacement for `RunAsManager`] though one is being considered.
  390. It is quite straightforward to adapt a `RunAsManager`, though, to the `AuthorizationManager` API, if needed.
  391. Here is some pseudocode to get you started:
  392. [tabs]
  393. ======
  394. Java::
  395. +
  396. [source,java,role="primary"]
  397. ----
  398. public final class RunAsAuthorizationManagerAdapter<T> implements AuthorizationManager<T> {
  399. private final RunAsManager runAs = new RunAsManagerImpl();
  400. private final SecurityMetadataSource metadata;
  401. private final AuthorizationManager<T> authorization;
  402. // ... constructor
  403. public AuthorizationDecision check(Supplier<Authentication> authentication, T object) {
  404. Supplier<Authentication> wrapped = (auth) -> {
  405. List<ConfigAttribute> attributes = this.metadata.getAttributes(object);
  406. return this.runAs.buildRunAs(auth, object, attributes);
  407. };
  408. return this.authorization.check(wrapped, object);
  409. }
  410. }
  411. ----
  412. ======
  413. Once you have implemented `AuthorizationManager`, please follow the details in the reference manual for xref:servlet/authorization/method-security.adoc#jc-method-security-custom-authorization-manager[adding a custom `AuthorizationManager`].
  414. [[servlet-check-for-annotationconfigurationexceptions]]
  415. === Check for ``AnnotationConfigurationException``s
  416. `@EnableMethodSecurity` and `<method-security>` activate stricter enforcement of Spring Security's non-repeatable or otherwise incompatible annotations.
  417. If after moving to either you see ``AnnotationConfigurationException``s in your logs, follow the instructions in the exception message to clean up your application's method security annotation usage.
  418. == Use `AuthorizationManager` for Message Security
  419. xref:servlet/integrations/websocket.adoc[Message Security] has been xref:servlet/integrations/websocket.adoc#websocket-configuration[improved] through {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[the `AuthorizationManager` API] and direct use of Spring AOP.
  420. Should you run into trouble with making these changes, you can follow the <<servlet-authorizationmanager-messages-opt-out,opt out steps>> at the end of this section.
  421. === Ensure all messages have defined authorization rules
  422. The now-deprecated {security-api-url}org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurer.html[message security support] permits all messages by default.
  423. xref:servlet/integrations/websocket.adoc[The new support] has the stronger default of denying all messages.
  424. To prepare for this, ensure that authorization rules exist are declared for every request.
  425. For example, an application configuration like:
  426. [tabs]
  427. ======
  428. Java::
  429. +
  430. [source,java,role="primary"]
  431. ----
  432. @Override
  433. protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
  434. messages
  435. .simpDestMatchers("/user/queue/errors").permitAll()
  436. .simpDestMatchers("/admin/**").hasRole("ADMIN");
  437. }
  438. ----
  439. Kotlin::
  440. +
  441. [source,kotlin,role="secondary"]
  442. ----
  443. override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
  444. messages
  445. .simpDestMatchers("/user/queue/errors").permitAll()
  446. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  447. }
  448. ----
  449. Xml::
  450. +
  451. [source,xml,role="secondary"]
  452. ----
  453. <websocket-message-broker>
  454. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  455. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  456. </websocket-message-broker>
  457. ----
  458. ======
  459. should change to:
  460. [tabs]
  461. ======
  462. Java::
  463. +
  464. [source,java,role="primary"]
  465. ----
  466. @Override
  467. protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
  468. messages
  469. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  470. .simpDestMatchers("/user/queue/errors").permitAll()
  471. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  472. .anyMessage().denyAll();
  473. }
  474. ----
  475. Kotlin::
  476. +
  477. [source,kotlin,role="secondary"]
  478. ----
  479. override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
  480. messages
  481. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  482. .simpDestMatchers("/user/queue/errors").permitAll()
  483. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  484. .anyMessage().denyAll()
  485. }
  486. ----
  487. Xml::
  488. +
  489. [source,xml,role="secondary"]
  490. ----
  491. <websocket-message-broker>
  492. <intercept-message type="CONNECT" access="permitAll"/>
  493. <intercept-message type="DISCONNECT" access="permitAll"/>
  494. <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
  495. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  496. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  497. <intercept-message pattern="/**" access="denyAll"/>
  498. </websocket-message-broker>
  499. ----
  500. ======
  501. === Add `@EnableWebSocketSecurity`
  502. [NOTE]
  503. ====
  504. If you want to have CSRF disabled and you are using Java configuration, the migration steps are slightly different.
  505. Instead of using `@EnableWebSocketSecurity`, you will override the appropriate methods in `WebSocketMessageBrokerConfigurer` yourself.
  506. Please see xref:servlet/integrations/websocket.adoc#websocket-sameorigin-disable[the reference manual] for details about this step.
  507. ====
  508. If you are using Java Configuration, add {security-api-url}org/springframework/security/config/annotation/web/socket/EnableWebSocketSecurity.html[`@EnableWebSocketSecurity`] to your application.
  509. For example, you can add it to your websocket security configuration class, like so:
  510. [tabs]
  511. ======
  512. Java::
  513. +
  514. [source,java,role="primary"]
  515. ----
  516. @EnableWebSocketSecurity
  517. @Configuration
  518. public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
  519. // ...
  520. }
  521. ----
  522. Kotlin::
  523. +
  524. [source,kotlin,role="secondary"]
  525. ----
  526. @EnableWebSocketSecurity
  527. @Configuration
  528. class WebSocketSecurityConfig: AbstractSecurityWebSocketMessageBrokerConfigurer() {
  529. // ...
  530. }
  531. ----
  532. ======
  533. This will make a prototype instance of `MessageMatcherDelegatingAuthorizationManager.Builder` available to encourage configuration by composition instead of extension.
  534. === Use an `AuthorizationManager<Message<?>>` instance
  535. To start using `AuthorizationManager`, you can set the `use-authorization-manager` attribute in XML or you can publish an `AuthorizationManager<Message<?>>` `@Bean` in Java.
  536. For example, the following application configuration:
  537. [tabs]
  538. ======
  539. Java::
  540. +
  541. [source,java,role="primary"]
  542. ----
  543. @Override
  544. protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
  545. messages
  546. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  547. .simpDestMatchers("/user/queue/errors").permitAll()
  548. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  549. .anyMessage().denyAll();
  550. }
  551. ----
  552. Kotlin::
  553. +
  554. [source,kotlin,role="secondary"]
  555. ----
  556. override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
  557. messages
  558. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  559. .simpDestMatchers("/user/queue/errors").permitAll()
  560. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  561. .anyMessage().denyAll()
  562. }
  563. ----
  564. Xml::
  565. +
  566. [source,xml,role="secondary"]
  567. ----
  568. <websocket-message-broker>
  569. <intercept-message type="CONNECT" access="permitAll"/>
  570. <intercept-message type="DISCONNECT" access="permitAll"/>
  571. <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
  572. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  573. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  574. <intercept-message pattern="/**" access="denyAll"/>
  575. </websocket-message-broker>
  576. ----
  577. ======
  578. changes to:
  579. [tabs]
  580. ======
  581. Java::
  582. +
  583. [source,java,role="primary"]
  584. ----
  585. @Bean
  586. AuthorizationManager<Message<?>> messageSecurity(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
  587. messages
  588. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  589. .simpDestMatchers("/user/queue/errors").permitAll()
  590. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  591. .anyMessage().denyAll();
  592. return messages.build();
  593. }
  594. ----
  595. Kotlin::
  596. +
  597. [source,kotlin,role="secondary"]
  598. ----
  599. @Bean
  600. fun messageSecurity(val messages: MessageMatcherDelegatingAuthorizationManager.Builder): AuthorizationManager<Message<?>> {
  601. messages
  602. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  603. .simpDestMatchers("/user/queue/errors").permitAll()
  604. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  605. .anyMessage().denyAll()
  606. return messages.build()
  607. }
  608. ----
  609. Xml::
  610. +
  611. [source,xml,role="secondary"]
  612. ----
  613. <websocket-message-broker use-authorization-manager="true">
  614. <intercept-message type="CONNECT" access="permitAll"/>
  615. <intercept-message type="DISCONNECT" access="permitAll"/>
  616. <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
  617. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  618. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  619. <intercept-message pattern="/**" access="denyAll"/>
  620. </websocket-message-broker>
  621. ----
  622. ======
  623. === Stop Implementing `AbstractSecurityWebSocketMessageBrokerConfigurer`
  624. If you are using Java configuration, you can now simply extend `WebSocketMessageBrokerConfigurer`.
  625. For example, if your class that extends `AbstractSecurityWebSocketMessageBrokerConfigurer` is called `WebSocketSecurityConfig`, then:
  626. [tabs]
  627. ======
  628. Java::
  629. +
  630. [source,java,role="primary"]
  631. ----
  632. @EnableWebSocketSecurity
  633. @Configuration
  634. public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
  635. // ...
  636. }
  637. ----
  638. Kotlin::
  639. +
  640. [source,kotlin,role="secondary"]
  641. ----
  642. @EnableWebSocketSecurity
  643. @Configuration
  644. class WebSocketSecurityConfig: AbstractSecurityWebSocketMessageBrokerConfigurer() {
  645. // ...
  646. }
  647. ----
  648. ======
  649. changes to:
  650. [tabs]
  651. ======
  652. Java::
  653. +
  654. [source,java,role="primary"]
  655. ----
  656. @EnableWebSocketSecurity
  657. @Configuration
  658. public class WebSocketSecurityConfig implements WebSocketMessageBrokerConfigurer {
  659. // ...
  660. }
  661. ----
  662. Kotlin::
  663. +
  664. [source,kotlin,role="secondary"]
  665. ----
  666. @EnableWebSocketSecurity
  667. @Configuration
  668. class WebSocketSecurityConfig: WebSocketMessageBrokerConfigurer {
  669. // ...
  670. }
  671. ----
  672. ======
  673. This also implies that you will need to xref:servlet/integrations/websocket.adoc#websocket-authorization[use a `MessageMatcherDelegationAuthorizationManager`] to specify your authorization rules.
  674. [[servlet-authorizationmanager-messages-opt-out]]
  675. === Opt-out Steps
  676. In case you had trouble, take a look at these scenarios for optimal opt out behavior:
  677. ==== I cannot declare an authorization rule for all requests
  678. If you are having trouble setting an `anyRequest` authorization rule of `denyAll`, please use {security-api-url}org/springframework/security/messaging/access/intercept/MessageMatcherDelegatingAuthorizationManager.Builder.Constraint.html#permitAll()[`permitAll`] instead, like so:
  679. [tabs]
  680. ======
  681. Java::
  682. +
  683. [source,java,role="primary"]
  684. ----
  685. @Bean
  686. AuthorizationManager<Message<?>> messageSecurity(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
  687. messages
  688. .simpDestMatchers("/user/queue/errors").permitAll()
  689. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  690. // ...
  691. .anyMessage().permitAll();
  692. return messages.build();
  693. }
  694. ----
  695. Kotlin::
  696. +
  697. [source,kotlin,role="secondary"]
  698. ----
  699. @Bean
  700. fun messageSecurity(val messages: MessageMatcherDelegatingAuthorizationManager.Builder): AuthorizationManager<Message<?>> {
  701. messages
  702. .simpDestMatchers("/user/queue/errors").permitAll()
  703. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  704. // ...
  705. .anyMessage().permitAll();
  706. return messages.build()
  707. }
  708. ----
  709. Xml::
  710. +
  711. [source,xml,role="secondary"]
  712. ----
  713. <websocket-message-broker use-authorization-manager="true">
  714. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  715. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  716. <!-- ... -->
  717. <intercept-message pattern="/**" access="permitAll"/>
  718. </websocket-message-broker>
  719. ----
  720. ======
  721. ==== I cannot get CSRF working, need some other `AbstractSecurityWebSocketMessageBrokerConfigurer` feature, or am having trouble with `AuthorizationManager`
  722. In the case of Java, you may continue using `AbstractMessageSecurityWebSocketMessageBrokerConfigurer`.
  723. Even though it is deprecated, it will not be removed in 6.0.
  724. In the case of XML, you can opt out of `AuthorizationManager` by setting `use-authorization-manager="false"`:
  725. .Xml
  726. [source,xml,role="secondary"]
  727. ----
  728. <websocket-message-broker>
  729. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  730. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  731. </websocket-message-broker>
  732. ----
  733. to:
  734. .Xml
  735. [source,xml,role="secondary"]
  736. ----
  737. <websocket-message-broker use-authorization-manager="false">
  738. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  739. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  740. </websocket-message-broker>
  741. ----
  742. == Use `AuthorizationManager` for Request Security
  743. xref:servlet/authorization/authorize-requests.adoc[HTTP Request Security] has been xref:servlet/authorization/authorize-http-requests.adoc[simplified] through {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[the `AuthorizationManager` API].
  744. Should you run into trouble with making these changes, you can follow the <<servlet-authorizationmanager-requests-opt-out,opt out steps>> at the end of this section.
  745. === Ensure that all requests have defined authorization rules
  746. In Spring Security 5.8 and earlier, requests with no authorization rule are permitted by default.
  747. It is a stronger security position to deny by default, thus requiring that authorization rules be clearly defined for every endpoint.
  748. As such, in 6.0, Spring Security by default denies any request that is missing an authorization rule.
  749. The simplest way to prepare for this change is to introduce an appropriate {security-api-url}org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.html#anyRequest()[`anyRequest`] rule as the last authorization rule.
  750. The recommendation is {security-api-url}org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationConfigurer.AuthorizedUrl.html#denyAll()[`denyAll`] since that is the implied 6.0 default.
  751. [NOTE]
  752. ====
  753. You may already have an `anyRequest` rule defined that you are happy with in which case this step can be skipped.
  754. ====
  755. Adding `denyAll` to the end looks like changing:
  756. [tabs]
  757. ======
  758. Java::
  759. +
  760. [source,java,role="primary"]
  761. ----
  762. http
  763. .authorizeRequests((authorize) -> authorize
  764. .filterSecurityInterceptorOncePerRequest(true)
  765. .mvcMatchers("/app/**").hasRole("APP")
  766. // ...
  767. )
  768. // ...
  769. ----
  770. Kotlin::
  771. +
  772. [source,kotlin,role="secondary"]
  773. ----
  774. http {
  775. authorizeRequests {
  776. filterSecurityInterceptorOncePerRequest = true
  777. authorize("/app/**", hasRole("APP"))
  778. // ...
  779. }
  780. }
  781. ----
  782. Xml::
  783. +
  784. [source,xml,role="secondary"]
  785. ----
  786. <http once-per-request="true">
  787. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  788. <!-- ... -->
  789. </http>
  790. ----
  791. ======
  792. to:
  793. [tabs]
  794. ======
  795. Java::
  796. +
  797. [source,java,role="primary"]
  798. ----
  799. http
  800. .authorizeRequests((authorize) -> authorize
  801. .filterSecurityInterceptorOncePerRequest(true)
  802. .mvcMatchers("/app/**").hasRole("APP")
  803. // ...
  804. .anyRequest().denyAll()
  805. )
  806. // ...
  807. ----
  808. Kotlin::
  809. +
  810. [source,kotlin,role="secondary"]
  811. ----
  812. http {
  813. authorizeRequests {
  814. filterSecurityInterceptorOncePerRequest = true
  815. authorize("/app/**", hasRole("APP"))
  816. // ...
  817. authorize(anyRequest, denyAll)
  818. }
  819. }
  820. ----
  821. Xml::
  822. +
  823. [source,xml,role="secondary"]
  824. ----
  825. <http once-per-request="true">
  826. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  827. <!-- ... -->
  828. <intercept-url pattern="/**" access="denyAll"/>
  829. </http>
  830. ----
  831. ======
  832. If you have already migrated to `authorizeHttpRequests`, the recommended change is the same.
  833. === Switch to `AuthorizationManager`
  834. To opt in to using `AuthorizationManager`, you can use `authorizeHttpRequests` or xref:servlet/appendix/namespace/http.adoc#nsa-http-use-authorization-manager[`use-authorization-manager`] for Java or XML, respectively.
  835. Change:
  836. [tabs]
  837. ======
  838. Java::
  839. +
  840. [source,java,role="primary"]
  841. ----
  842. http
  843. .authorizeRequests((authorize) -> authorize
  844. .filterSecurityInterceptorOncePerRequest(true)
  845. .mvcMatchers("/app/**").hasRole("APP")
  846. // ...
  847. .anyRequest().denyAll()
  848. )
  849. // ...
  850. ----
  851. Kotlin::
  852. +
  853. [source,kotlin,role="secondary"]
  854. ----
  855. http {
  856. authorizeRequests {
  857. filterSecurityInterceptorOncePerRequest = true
  858. authorize("/app/**", hasRole("APP"))
  859. // ...
  860. authorize(anyRequest, denyAll)
  861. }
  862. }
  863. ----
  864. Xml::
  865. +
  866. [source,xml,role="secondary"]
  867. ----
  868. <http once-per-request="true">
  869. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  870. <!-- ... -->
  871. <intercept-url pattern="/**" access="denyAll"/>
  872. </http>
  873. ----
  874. ======
  875. to:
  876. [tabs]
  877. ======
  878. Java::
  879. +
  880. [source,java,role="primary"]
  881. ----
  882. http
  883. .authorizeHttpRequests((authorize) -> authorize
  884. .shouldFilterAllDispatcherTypes(false)
  885. .mvcMatchers("/app/**").hasRole("APP")
  886. // ...
  887. .anyRequest().denyAll()
  888. )
  889. // ...
  890. ----
  891. Kotlin::
  892. +
  893. [source,kotlin,role="secondary"]
  894. ----
  895. http {
  896. authorizeHttpRequests {
  897. shouldFilterAllDispatcherTypes = false
  898. authorize("/app/**", hasRole("APP"))
  899. // ...
  900. authorize(anyRequest, denyAll)
  901. }
  902. }
  903. ----
  904. Xml::
  905. +
  906. [source,xml,role="secondary"]
  907. ----
  908. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  909. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  910. <!-- ... -->
  911. <intercept-url pattern="/**" access="denyAll"/>
  912. </http>
  913. ----
  914. ======
  915. === Migrate `hasIpAddress` to `access(AuthorizationManager)`
  916. `hasIpAddress` has no DSL equivalent in `authorizeHttpRequests`.
  917. As such, you need to change any called to `hasIpAddress` to using an `AuthorizationManager`.
  918. First, construct an `IpAddressMatcher` like so:
  919. ====
  920. .Java
  921. [source,java,role="primary"]
  922. ----
  923. IpAddressMatcher hasIpAddress = new IpAddressMatcher("127.0.0.1");
  924. ----
  925. ====
  926. And then change from this:
  927. ====
  928. .Java
  929. [source,java,role="primary"]
  930. ----
  931. http
  932. .authorizeRequests((authorize) -> authorize
  933. .mvcMatchers("/app/**").hasIpAddress("127.0.0.1")
  934. // ...
  935. .anyRequest().denyAll()
  936. )
  937. // ...
  938. ----
  939. ====
  940. to this:
  941. ====
  942. .Java
  943. [source,java,role="primary"]
  944. ----
  945. http
  946. .authorizeHttpRequests((authorize) -> authorize
  947. .requestMatchers("/app/**").access((authentication, context) ->
  948. new AuthorizationDecision(hasIpAddress.matches(context.getRequest()))
  949. // ...
  950. .anyRequest().denyAll()
  951. )
  952. // ...
  953. ----
  954. ====
  955. [NOTE]
  956. Securing by IP Address is quite fragile to begin with.
  957. For that reason, there are no plans to port this support over to `authorizeHttpRequests`.
  958. === Migrate SpEL expressions to `AuthorizationManager`
  959. For authorization rules, Java tends to be easier to test and maintain than SpEL.
  960. As such, `authorizeHttpRequests` does not have a method for declaring a `String` SpEL.
  961. Instead, you can implement your own `AuthorizationManager` implementation or use `WebExpressionAuthorizationManager`.
  962. For completeness, both options will be demonstrated.
  963. First, if you have the following SpEL:
  964. [tabs]
  965. ======
  966. Java::
  967. +
  968. [source,java,role="primary"]
  969. ----
  970. http
  971. .authorizeRequests((authorize) -> authorize
  972. .filterSecurityInterceptorOncePerRequest(true)
  973. .mvcMatchers("/complicated/**").access("hasRole('ADMIN') || hasAuthority('SCOPE_read')")
  974. // ...
  975. .anyRequest().denyAll()
  976. )
  977. // ...
  978. ----
  979. Kotlin::
  980. +
  981. [source,kotlin,role="secondary"]
  982. ----
  983. http {
  984. authorizeRequests {
  985. filterSecurityInterceptorOncePerRequest = true
  986. authorize("/complicated/**", access("hasRole('ADMIN') || hasAuthority('SCOPE_read')"))
  987. // ...
  988. authorize(anyRequest, denyAll)
  989. }
  990. }
  991. ----
  992. ======
  993. Then you can compose your own `AuthorizationManager` with Spring Security authorization primitives like so:
  994. [tabs]
  995. ======
  996. Java::
  997. +
  998. [source,java,role="primary"]
  999. ----
  1000. http
  1001. .authorizeHttpRequests((authorize) -> authorize
  1002. .shouldFilterAllDispatcherTypes(false)
  1003. .mvcMatchers("/complicated/**").access(anyOf(hasRole("ADMIN"), hasAuthority("SCOPE_read"))
  1004. // ...
  1005. .anyRequest().denyAll()
  1006. )
  1007. // ...
  1008. ----
  1009. Kotlin::
  1010. +
  1011. [source,kotlin,role="secondary"]
  1012. ----
  1013. http {
  1014. authorizeHttpRequests {
  1015. shouldFilterAllDispatcherTypes = false
  1016. authorize("/complicated/**", access(anyOf(hasRole("ADMIN"), hasAuthority("SCOPE_read"))
  1017. // ...
  1018. authorize(anyRequest, denyAll)
  1019. }
  1020. }
  1021. ----
  1022. ======
  1023. Or you can use `WebExpressionAuthorizationManager` in the following way:
  1024. [tabs]
  1025. ======
  1026. Java::
  1027. +
  1028. [source,java,role="primary"]
  1029. ----
  1030. http
  1031. .authorizeRequests((authorize) -> authorize
  1032. .filterSecurityInterceptorOncePerRequest(true)
  1033. .mvcMatchers("/complicated/**").access(
  1034. new WebExpressionAuthorizationManager("hasRole('ADMIN') || hasAuthority('SCOPE_read')")
  1035. )
  1036. // ...
  1037. .anyRequest().denyAll()
  1038. )
  1039. // ...
  1040. ----
  1041. Kotlin::
  1042. +
  1043. [source,kotlin,role="secondary"]
  1044. ----
  1045. http {
  1046. authorizeRequests {
  1047. filterSecurityInterceptorOncePerRequest = true
  1048. authorize("/complicated/**", access(
  1049. WebExpressionAuthorizationManager("hasRole('ADMIN') || hasAuthority('SCOPE_read')"))
  1050. )
  1051. // ...
  1052. authorize(anyRequest, denyAll)
  1053. }
  1054. }
  1055. ----
  1056. ======
  1057. [[switch-filter-all-dispatcher-types]]
  1058. === Switch to filter all dispatcher types
  1059. Spring Security 5.8 and earlier only xref:servlet/authorization/architecture.adoc[perform authorization] once per request.
  1060. This means that dispatcher types like `FORWARD` and `INCLUDE` that run after `REQUEST` are not secured by default.
  1061. It's recommended that Spring Security secure all dispatch types.
  1062. As such, in 6.0, Spring Security changes this default.
  1063. So, finally, change your authorization rules to filter all dispatcher types.
  1064. To do this, you should change:
  1065. [tabs]
  1066. ======
  1067. Java::
  1068. +
  1069. [source,java,role="primary"]
  1070. ----
  1071. http
  1072. .authorizeHttpRequests((authorize) -> authorize
  1073. .shouldFilterAllDispatcherTypes(false)
  1074. .mvcMatchers("/app/**").hasRole("APP")
  1075. // ...
  1076. .anyRequest().denyAll()
  1077. )
  1078. // ...
  1079. ----
  1080. Kotlin::
  1081. +
  1082. [source,kotlin,role="secondary"]
  1083. ----
  1084. http {
  1085. authorizeHttpRequests {
  1086. shouldFilterAllDispatcherTypes = false
  1087. authorize("/app/**", hasRole("APP"))
  1088. // ...
  1089. authorize(anyRequest, denyAll)
  1090. }
  1091. }
  1092. ----
  1093. Xml::
  1094. +
  1095. [source,xml,role="secondary"]
  1096. ----
  1097. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  1098. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1099. <!-- ... -->
  1100. <intercept-url pattern="/**" access="denyAll"/>
  1101. </http>
  1102. ----
  1103. ======
  1104. to:
  1105. [tabs]
  1106. ======
  1107. Java::
  1108. +
  1109. [source,java,role="primary"]
  1110. ----
  1111. http
  1112. .authorizeHttpRequests((authorize) -> authorize
  1113. .shouldFilterAllDispatcherTypes(true)
  1114. .mvcMatchers("/app/**").hasRole("APP")
  1115. // ...
  1116. .anyRequest().denyAll()
  1117. )
  1118. // ...
  1119. ----
  1120. Kotlin::
  1121. +
  1122. [source,kotlin,role="secondary"]
  1123. ----
  1124. http {
  1125. authorizeHttpRequests {
  1126. shouldFilterAllDispatcherTypes = true
  1127. authorize("/app/**", hasRole("APP"))
  1128. // ...
  1129. authorize(anyRequest, denyAll)
  1130. }
  1131. }
  1132. ----
  1133. Xml::
  1134. +
  1135. [source,xml,role="secondary"]
  1136. ----
  1137. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  1138. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1139. <!-- ... -->
  1140. <intercept-url pattern="/**" access="denyAll"/>
  1141. </http>
  1142. ----
  1143. ======
  1144. And, the `FilterChainProxy` should be registered for all dispatcher types as well.
  1145. If you are using Spring Boot, https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#application-properties.security.spring.security.filter.dispatcher-types[you have to change the `spring.security.filter.dispatcher-types` property] to include all dispatcher types:
  1146. [tabs]
  1147. ======
  1148. application.properties::
  1149. +
  1150. [source,properties,role="primary"]
  1151. ----
  1152. spring.security.filter.dispatcher-types=request,async,error,forward,include
  1153. ----
  1154. ======
  1155. If you are xref:servlet/configuration/java.adoc#_abstractsecuritywebapplicationinitializer[using the `AbstractSecurityWebApplicationInitializer`] you should override the `getSecurityDispatcherTypes` method and return all dispatcher types:
  1156. [tabs]
  1157. ======
  1158. Java::
  1159. +
  1160. [source,java,role="primary"]
  1161. ----
  1162. import org.springframework.security.web.context.*;
  1163. public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
  1164. @Override
  1165. protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
  1166. return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC,
  1167. DispatcherType.FORWARD, DispatcherType.INCLUDE);
  1168. }
  1169. }
  1170. ----
  1171. ======
  1172. ==== Permit `FORWARD` when using Spring MVC
  1173. If you are using {spring-framework-reference-url}/web.html#mvc-viewresolver[Spring MVC to resolve view names], you will need to permit `FORWARD` requests.
  1174. This is because when Spring MVC detects a mapping between view name and the actual views, it will perform a forward to the view.
  1175. As we saw on the <<switch-filter-all-dispatcher-types,previous section>>, Spring Security 6.0 will apply authorization to `FORWARD` requests by default.
  1176. Consider the following common configuration:
  1177. [tabs]
  1178. ======
  1179. Java::
  1180. +
  1181. [source,java,role="primary"]
  1182. ----
  1183. @Bean
  1184. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  1185. http
  1186. .authorizeHttpRequests((authorize) -> authorize
  1187. .shouldFilterAllDispatcherTypes(true)
  1188. .requestMatchers("/").authenticated()
  1189. .anyRequest().denyAll()
  1190. )
  1191. .formLogin((form) -> form
  1192. .loginPage("/login")
  1193. .permitAll()
  1194. ));
  1195. return http.build();
  1196. }
  1197. ----
  1198. ======
  1199. and one of the following equivalents MVC view mapping configurations:
  1200. [tabs]
  1201. ======
  1202. Java::
  1203. +
  1204. [source,java,role="primary"]
  1205. ----
  1206. @Controller
  1207. public class MyController {
  1208. @GetMapping("/login")
  1209. public String login() {
  1210. return "login";
  1211. }
  1212. }
  1213. ----
  1214. ======
  1215. [tabs]
  1216. ======
  1217. Java::
  1218. +
  1219. [source,java,role="primary"]
  1220. ----
  1221. @Configuration
  1222. public class MyWebMvcConfigurer implements WebMvcConfigurer {
  1223. @Override
  1224. public void addViewControllers(ViewControllerRegistry registry) {
  1225. registry.addViewController("/login").setViewName("login");
  1226. }
  1227. }
  1228. ----
  1229. ======
  1230. With either configuration, when there is a request to `/login`, Spring MVC will perform a *forward* to the view `login`, which, with the default configuration, is under `src/main/resources/templates/login.html` path.
  1231. The security configuration permits requests to `/login` but every other request will be denied, including the `FORWARD` request to the view under `/templates/login.html`.
  1232. To fix this, you should configure Spring Security to permit `FORWARD` requests:
  1233. [tabs]
  1234. ======
  1235. Java::
  1236. +
  1237. [source,java,role="primary"]
  1238. ----
  1239. http
  1240. .authorizeHttpRequests((authorize) -> authorize
  1241. .shouldFilterAllDispatcherTypes(true)
  1242. .dispatcherTypeMatchers(DispatcherType.FORWARD).permitAll()
  1243. .anyRequest().denyAll()
  1244. )
  1245. // ...
  1246. ----
  1247. Kotlin::
  1248. +
  1249. [source,kotlin,role="secondary"]
  1250. ----
  1251. http {
  1252. authorizeHttpRequests {
  1253. shouldFilterAllDispatcherTypes = true
  1254. authorize(DispatcherTypeRequestMatcher(DispatcherType.FORWARD), permitAll)
  1255. authorize(anyRequest, denyAll)
  1256. }
  1257. }
  1258. ----
  1259. Xml::
  1260. +
  1261. [source,xml,role="secondary"]
  1262. ----
  1263. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  1264. <intercept-url request-matcher-ref="forwardRequestMatcher" access="permitAll()" />
  1265. <!-- ... -->
  1266. <intercept-url pattern="/**" access="denyAll"/>
  1267. </http>
  1268. <bean name="forwardRequestMatcher" class="org.springframework.security.web.util.matcher.DispatcherTypeRequestMatcher">
  1269. <constructor-arg value="FORWARD"/>
  1270. </bean>
  1271. ----
  1272. ======
  1273. === Replace any custom filter-security ``AccessDecisionManager``s
  1274. Your application may have a custom {security-api-url}org/springframework/security/access/AccessDecisionManager.html[`AccessDecisionManager`] or {security-api-url}org/springframework/security/access/AccessDecisionVoter.html[`AccessDecisionVoter`] arrangement.
  1275. The preparation strategy will depend on your reason for each arrangement.
  1276. Read on to find the best match for your situation.
  1277. ==== I use `UnanimousBased`
  1278. If your application uses {security-api-url}org/springframework/security/access/vote/UnanimousBased.html[`UnanimousBased`], you should first adapt or replace any ``AccessDecisionVoter``s and then you can construct an `AuthorizationManager` like so:
  1279. [tabs]
  1280. ======
  1281. Java::
  1282. +
  1283. [source,java,role="primary"]
  1284. ----
  1285. @Bean
  1286. AuthorizationManager<RequestAuthorizationContext> requestAuthorization() {
  1287. PolicyAuthorizationManager policy = ...;
  1288. LocalAuthorizationManager local = ...;
  1289. return AuthorizationManagers.allOf(policy, local);
  1290. }
  1291. ----
  1292. Kotlin::
  1293. +
  1294. [source,kotlin,role="secondary"]
  1295. ----
  1296. @Bean
  1297. fun requestAuthorization(): AuthorizationManager<RequestAuthorizationContext> {
  1298. val policy: PolicyAuthorizationManager = ...
  1299. val local: LocalAuthorizationManager = ...
  1300. return AuthorizationManagers.allOf(policy, local)
  1301. }
  1302. ----
  1303. Xml::
  1304. +
  1305. [source,xml,role="secondary"]
  1306. ----
  1307. <bean id="requestAuthorization" class="org.springframework.security.authorization.AuthorizationManagers"
  1308. factory-method="allOf">
  1309. <constructor-arg>
  1310. <util:list>
  1311. <bean class="my.PolicyAuthorizationManager"/>
  1312. <bean class="my.LocalAuthorizationManager"/>
  1313. </util:list>
  1314. </constructor-arg>
  1315. </bean>
  1316. ----
  1317. ======
  1318. then, wire it into the DSL like so:
  1319. [tabs]
  1320. ======
  1321. Java::
  1322. +
  1323. [source,java,role="primary"]
  1324. ----
  1325. http
  1326. .authorizeHttpRequests((authorize) -> authorize.anyRequest().access(requestAuthorization))
  1327. // ...
  1328. ----
  1329. Kotlin::
  1330. +
  1331. [source,kotlin,role="secondary"]
  1332. ----
  1333. http {
  1334. authorizeHttpRequests {
  1335. authorize(anyRequest, requestAuthorization)
  1336. }
  1337. // ...
  1338. }
  1339. ----
  1340. Xml::
  1341. +
  1342. [source,xml,role="secondary"]
  1343. ----
  1344. <http authorization-manager-ref="requestAuthorization"/>
  1345. ----
  1346. ======
  1347. [NOTE]
  1348. ====
  1349. `authorizeHttpRequests` is designed so that you can apply a custom `AuthorizationManager` to any url pattern.
  1350. See xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[the reference] for more details.
  1351. ====
  1352. ==== I use `AffirmativeBased`
  1353. If your application uses {security-api-url}org/springframework/security/access/vote/AffirmativeBased.html[`AffirmativeBased`], then you can construct an equivalent {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`], like so:
  1354. [tabs]
  1355. ======
  1356. Java::
  1357. +
  1358. [source,java,role="primary"]
  1359. ----
  1360. @Bean
  1361. AuthorizationManager<RequestAuthorizationContext> requestAuthorization() {
  1362. PolicyAuthorizationManager policy = ...;
  1363. LocalAuthorizationManager local = ...;
  1364. return AuthorizationManagers.anyOf(policy, local);
  1365. }
  1366. ----
  1367. Kotlin::
  1368. +
  1369. [source,kotlin,role="secondary"]
  1370. ----
  1371. @Bean
  1372. fun requestAuthorization(): AuthorizationManager<RequestAuthorizationContext> {
  1373. val policy: PolicyAuthorizationManager = ...
  1374. val local: LocalAuthorizationManager = ...
  1375. return AuthorizationManagers.anyOf(policy, local)
  1376. }
  1377. ----
  1378. Xml::
  1379. +
  1380. [source,xml,role="secondary"]
  1381. ----
  1382. <bean id="requestAuthorization" class="org.springframework.security.authorization.AuthorizationManagers"
  1383. factory-method="anyOf">
  1384. <constructor-arg>
  1385. <util:list>
  1386. <bean class="my.PolicyAuthorizationManager"/>
  1387. <bean class="my.LocalAuthorizationManager"/>
  1388. </util:list>
  1389. </constructor-arg>
  1390. </bean>
  1391. ----
  1392. ======
  1393. then, wire it into the DSL like so:
  1394. [tabs]
  1395. ======
  1396. Java::
  1397. +
  1398. [source,java,role="primary"]
  1399. ----
  1400. http
  1401. .authorizeHttpRequests((authorize) -> authorize.anyRequest().access(requestAuthorization))
  1402. // ...
  1403. ----
  1404. Kotlin::
  1405. +
  1406. [source,kotlin,role="secondary"]
  1407. ----
  1408. http {
  1409. authorizeHttpRequests {
  1410. authorize(anyRequest, requestAuthorization)
  1411. }
  1412. // ...
  1413. }
  1414. ----
  1415. Xml::
  1416. +
  1417. [source,xml,role="secondary"]
  1418. ----
  1419. <http authorization-manager-ref="requestAuthorization"/>
  1420. ----
  1421. ======
  1422. [NOTE]
  1423. ====
  1424. `authorizeHttpRequests` is designed so that you can apply a custom `AuthorizationManager` to any url pattern.
  1425. See xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[the reference] for more details.
  1426. ====
  1427. ==== I use `ConsensusBased`
  1428. There is no framework-provided equivalent for {security-api-url}org/springframework/security/access/vote/ConsensusBased.html[`ConsensusBased`].
  1429. In that case, please implement a composite {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] that takes the set of delegate ``AuthorizationManager``s into account.
  1430. Once you have implemented `AuthorizationManager`, please follow the details in the reference manual for xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[adding a custom `AuthorizationManager`].
  1431. ==== I use a custom `AccessDecisionVoter`
  1432. You should either change the class to implement {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] or create an adapter.
  1433. Without knowing what your custom voter is doing, it is impossible to recommend a general-purpose solution.
  1434. By way of example, though, here is what adapting {security-api-url}org/springframework/security/access/SecurityMetadataSource.html[`SecurityMetadataSource`] and {security-api-url}org/springframework/security/access/AccessDecisionVoter.html[`AccessDecisionVoter`] for `anyRequest().authenticated()` would look like:
  1435. [tabs]
  1436. ======
  1437. Java::
  1438. +
  1439. [source,java,role="primary"]
  1440. ----
  1441. public final class AnyRequestAuthenticatedAuthorizationManagerAdapter implements AuthorizationManager<RequestAuthorizationContext> {
  1442. private final SecurityMetadataSource metadata;
  1443. private final AccessDecisionVoter voter;
  1444. public PreAuthorizeAuthorizationManagerAdapter(SecurityExpressionHandler expressionHandler) {
  1445. Map<RequestMatcher, List<ConfigAttribute>> requestMap = Collections.singletonMap(
  1446. AnyRequestMatcher.INSTANCE, Collections.singletonList(new SecurityConfig("authenticated")));
  1447. this.metadata = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
  1448. WebExpressionVoter voter = new WebExpressionVoter();
  1449. voter.setExpressionHandler(expressionHandler);
  1450. this.voter = voter;
  1451. }
  1452. public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
  1453. List<ConfigAttribute> attributes = this.metadata.getAttributes(context);
  1454. int decision = this.voter.vote(authentication.get(), invocation, attributes);
  1455. if (decision == ACCESS_GRANTED) {
  1456. return new AuthorizationDecision(true);
  1457. }
  1458. if (decision == ACCESS_DENIED) {
  1459. return new AuthorizationDecision(false);
  1460. }
  1461. return null; // abstain
  1462. }
  1463. }
  1464. ----
  1465. ======
  1466. Once you have implemented `AuthorizationManager`, please follow the details in the reference manual for xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[adding a custom `AuthorizationManager`].
  1467. [[replace-hasrole-hasauthority]]
  1468. === Replace `hasRole` with `hasAuthority` if using `GrantedAuthorityDefaults`
  1469. Currently, the `hasRole` method inside `authorizeHttpRequests` does not support the `GrantedAuthorityDefaults` bean like the `authorizeRequests` does.
  1470. Therefore, if you are using `GrantedAuthorityDefaults` to change the prefix of your roles, you will need to use `hasAuthority` instead of `hasRole`.
  1471. For example, you will have to change from:
  1472. .authorizeRequests with custom role prefix
  1473. [source,java]
  1474. ----
  1475. @Bean
  1476. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  1477. http
  1478. .authorizeRequests((authorize) -> authorize
  1479. .anyRequest().hasRole("ADMIN")
  1480. );
  1481. return http.build();
  1482. }
  1483. @Bean
  1484. public GrantedAuthorityDefaults grantedAuthorityDefaults() {
  1485. return new GrantedAuthorityDefaults("MYPREFIX_");
  1486. }
  1487. ----
  1488. to:
  1489. .authorizeHttpRequests with hasAuthority and custom role prefix
  1490. [source,java]
  1491. ----
  1492. @Bean
  1493. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  1494. http
  1495. .authorizeHttpRequests((authorize) -> authorize
  1496. .anyRequest().hasAuthority("MYPREFIX_ADMIN")
  1497. );
  1498. return http.build();
  1499. }
  1500. ----
  1501. This should be supported in the future, see https://github.com/spring-projects/spring-security/issues/13215[gh-13227] for more details.
  1502. [[servlet-authorizationmanager-requests-opt-out]]
  1503. === Opt-out Steps
  1504. In case you had trouble, take a look at these scenarios for optimal opt out behavior:
  1505. ==== I cannot secure all dispatcher types
  1506. If you cannot secure all dispatcher types, first try and declare which dispatcher types should not require authorization like so:
  1507. [tabs]
  1508. ======
  1509. Java::
  1510. +
  1511. [source,java,role="primary"]
  1512. ----
  1513. http
  1514. .authorizeHttpRequests((authorize) -> authorize
  1515. .shouldFilterAllDispatcherTypes(true)
  1516. .dispatcherTypeMatchers(FORWARD, INCLUDE).permitAll()
  1517. .mvcMatchers("/app/**").hasRole("APP")
  1518. // ...
  1519. .anyRequest().denyAll()
  1520. )
  1521. // ...
  1522. ----
  1523. Kotlin::
  1524. +
  1525. [source,kotlin,role="secondary"]
  1526. ----
  1527. http {
  1528. authorizeHttpRequests {
  1529. shouldFilterAllDispatcherTypes = true
  1530. authorize(DispatcherTypeRequestMatcher(FORWARD, INCLUDE), permitAll)
  1531. authorize("/app/**", hasRole("APP"))
  1532. // ...
  1533. authorize(anyRequest, denyAll)
  1534. }
  1535. }
  1536. ----
  1537. Xml::
  1538. +
  1539. [source,xml,role="secondary"]
  1540. ----
  1541. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  1542. <intercept-url request-matcher-ref="dispatchers"/>
  1543. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1544. <!-- ... -->
  1545. <intercept-url pattern="/**" access="denyAll"/>
  1546. </http>
  1547. <bean id="dispatchers" class="org.springframework.security.web.util.matcher.DispatcherTypeRequestMatcher">
  1548. <constructor-arg>
  1549. <util:list value-type="javax.servlet.DispatcherType">
  1550. <value>FORWARD</value>
  1551. <value>INCLUDE</value>
  1552. </util:list>
  1553. </constructor-arg>
  1554. </bean>
  1555. ----
  1556. ======
  1557. Or, if that doesn't work, then you can explicitly opt out of the behavior by setting `filter-all-dispatcher-types` and `filterAllDispatcherTypes` to `false`:
  1558. [tabs]
  1559. ======
  1560. Java::
  1561. +
  1562. [source,java,role="primary"]
  1563. ----
  1564. http
  1565. .authorizeHttpRequests((authorize) -> authorize
  1566. .filterAllDispatcherTypes(false)
  1567. .mvcMatchers("/app/**").hasRole("APP")
  1568. // ...
  1569. )
  1570. // ...
  1571. ----
  1572. Kotlin::
  1573. +
  1574. [source,kotlin,role="secondary"]
  1575. ----
  1576. http {
  1577. authorizeHttpRequests {
  1578. filterAllDispatcherTypes = false
  1579. authorize("/messages/**", hasRole("APP"))
  1580. // ...
  1581. }
  1582. }
  1583. ----
  1584. Xml::
  1585. +
  1586. [source,xml,role="secondary"]
  1587. ----
  1588. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  1589. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1590. <!-- ... -->
  1591. </http>
  1592. ----
  1593. ======
  1594. or, if you are still using `authorizeRequests` or `use-authorization-manager="false"`, set `oncePerRequest` to `true`:
  1595. [tabs]
  1596. ======
  1597. Java::
  1598. +
  1599. [source,java,role="primary"]
  1600. ----
  1601. http
  1602. .authorizeRequests((authorize) -> authorize
  1603. .filterSecurityInterceptorOncePerRequest(true)
  1604. .mvcMatchers("/app/**").hasRole("APP")
  1605. // ...
  1606. )
  1607. // ...
  1608. ----
  1609. Kotlin::
  1610. +
  1611. [source,kotlin,role="secondary"]
  1612. ----
  1613. http {
  1614. authorizeRequests {
  1615. filterSecurityInterceptorOncePerRequest = true
  1616. authorize("/messages/**", hasRole("APP"))
  1617. // ...
  1618. }
  1619. }
  1620. ----
  1621. Xml::
  1622. +
  1623. [source,xml,role="secondary"]
  1624. ----
  1625. <http once-per-request="true" use-authorization-manager="false">
  1626. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1627. <!-- ... -->
  1628. </http>
  1629. ----
  1630. ======
  1631. ==== I cannot declare an authorization rule for all requests
  1632. If you are having trouble setting an `anyRequest` authorization rule of `denyAll`, please use {security-api-url}org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationConfigurer.AuthorizedUrl.html#permitAll()[`permitAll`] instead, like so:
  1633. [tabs]
  1634. ======
  1635. Java::
  1636. +
  1637. [source,java,role="primary"]
  1638. ----
  1639. http
  1640. .authorizeHttpReqeusts((authorize) -> authorize
  1641. .mvcMatchers("/app/*").hasRole("APP")
  1642. // ...
  1643. .anyRequest().permitAll()
  1644. )
  1645. ----
  1646. Kotlin::
  1647. +
  1648. [source,kotlin,role="secondary"]
  1649. ----
  1650. http {
  1651. authorizeHttpRequests {
  1652. authorize("/app*", hasRole("APP"))
  1653. // ...
  1654. authorize(anyRequest, permitAll)
  1655. }
  1656. }
  1657. ----
  1658. Xml::
  1659. +
  1660. [source,xml,role="secondary"]
  1661. ----
  1662. <http>
  1663. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1664. <!-- ... -->
  1665. <intercept-url pattern="/**" access="permitAll"/>
  1666. </http>
  1667. ----
  1668. ======
  1669. ==== I cannot migrate my SpEL or my `AccessDecisionManager`
  1670. If you are having trouble with SpEL, `AccessDecisionManager`, or there is some other feature that you are needing to keep using in `<http>` or `authorizeRequests`, try the following.
  1671. First, if you still need `authorizeRequests`, you are welcome to keep using it. Even though it is deprecated, it is not removed in 6.0.
  1672. Second, if you still need your custom `access-decision-manager-ref` or have some other reason to opt out of `AuthorizationManager`, do:
  1673. .Xml
  1674. [source,xml,role="secondary"]
  1675. ----
  1676. <http use-authorization-manager="false">
  1677. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1678. <!-- ... -->
  1679. </http>
  1680. ----