2
0

authorization.adoc 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983
  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. [[servlet-authorizationmanager-messages-opt-out]]
  674. === Opt-out Steps
  675. In case you had trouble, take a look at these scenarios for optimal opt out behavior:
  676. ==== I cannot declare an authorization rule for all requests
  677. 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:
  678. [tabs]
  679. ======
  680. Java::
  681. +
  682. [source,java,role="primary"]
  683. ----
  684. @Bean
  685. AuthorizationManager<Message<?>> messageSecurity(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
  686. messages
  687. .simpDestMatchers("/user/queue/errors").permitAll()
  688. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  689. // ...
  690. .anyMessage().permitAll();
  691. return messages.build();
  692. }
  693. ----
  694. Kotlin::
  695. +
  696. [source,kotlin,role="secondary"]
  697. ----
  698. @Bean
  699. fun messageSecurity(val messages: MessageMatcherDelegatingAuthorizationManager.Builder): AuthorizationManager<Message<?>> {
  700. messages
  701. .simpDestMatchers("/user/queue/errors").permitAll()
  702. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  703. // ...
  704. .anyMessage().permitAll();
  705. return messages.build()
  706. }
  707. ----
  708. Xml::
  709. +
  710. [source,xml,role="secondary"]
  711. ----
  712. <websocket-message-broker use-authorization-manager="true">
  713. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  714. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  715. <!-- ... -->
  716. <intercept-message pattern="/**" access="permitAll"/>
  717. </websocket-message-broker>
  718. ----
  719. ======
  720. ==== I cannot get CSRF working, need some other `AbstractSecurityWebSocketMessageBrokerConfigurer` feature, or am having trouble with `AuthorizationManager`
  721. In the case of Java, you may continue using `AbstractMessageSecurityWebSocketMessageBrokerConfigurer`.
  722. Even though it is deprecated, it will not be removed in 6.0.
  723. In the case of XML, you can opt out of `AuthorizationManager` by setting `use-authorization-manager="false"`:
  724. .Xml
  725. [source,xml,role="secondary"]
  726. ----
  727. <websocket-message-broker>
  728. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  729. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  730. </websocket-message-broker>
  731. ----
  732. to:
  733. .Xml
  734. [source,xml,role="secondary"]
  735. ----
  736. <websocket-message-broker use-authorization-manager="false">
  737. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  738. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  739. </websocket-message-broker>
  740. ----
  741. == Use `AuthorizationManager` for Request Security
  742. 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].
  743. 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.
  744. === Ensure that all requests have defined authorization rules
  745. In Spring Security 5.8 and earlier, requests with no authorization rule are permitted by default.
  746. It is a stronger security position to deny by default, thus requiring that authorization rules be clearly defined for every endpoint.
  747. As such, in 6.0, Spring Security by default denies any request that is missing an authorization rule.
  748. 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.
  749. 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.
  750. [NOTE]
  751. ====
  752. You may already have an `anyRequest` rule defined that you are happy with in which case this step can be skipped.
  753. ====
  754. Adding `denyAll` to the end looks like changing:
  755. [tabs]
  756. ======
  757. Java::
  758. +
  759. [source,java,role="primary"]
  760. ----
  761. http
  762. .authorizeRequests((authorize) -> authorize
  763. .filterSecurityInterceptorOncePerRequest(true)
  764. .mvcMatchers("/app/**").hasRole("APP")
  765. // ...
  766. )
  767. // ...
  768. ----
  769. Kotlin::
  770. +
  771. [source,kotlin,role="secondary"]
  772. ----
  773. http {
  774. authorizeRequests {
  775. filterSecurityInterceptorOncePerRequest = true
  776. authorize("/app/**", hasRole("APP"))
  777. // ...
  778. }
  779. }
  780. ----
  781. Xml::
  782. +
  783. [source,xml,role="secondary"]
  784. ----
  785. <http once-per-request="true">
  786. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  787. <!-- ... -->
  788. </http>
  789. ----
  790. ======
  791. to:
  792. [tabs]
  793. ======
  794. Java::
  795. +
  796. [source,java,role="primary"]
  797. ----
  798. http
  799. .authorizeRequests((authorize) -> authorize
  800. .filterSecurityInterceptorOncePerRequest(true)
  801. .mvcMatchers("/app/**").hasRole("APP")
  802. // ...
  803. .anyRequest().denyAll()
  804. )
  805. // ...
  806. ----
  807. Kotlin::
  808. +
  809. [source,kotlin,role="secondary"]
  810. ----
  811. http {
  812. authorizeRequests {
  813. filterSecurityInterceptorOncePerRequest = true
  814. authorize("/app/**", hasRole("APP"))
  815. // ...
  816. authorize(anyRequest, denyAll)
  817. }
  818. }
  819. ----
  820. Xml::
  821. +
  822. [source,xml,role="secondary"]
  823. ----
  824. <http once-per-request="true">
  825. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  826. <!-- ... -->
  827. <intercept-url pattern="/**" access="denyAll"/>
  828. </http>
  829. ----
  830. ======
  831. If you have already migrated to `authorizeHttpRequests`, the recommended change is the same.
  832. === Switch to `AuthorizationManager`
  833. 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.
  834. Change:
  835. [tabs]
  836. ======
  837. Java::
  838. +
  839. [source,java,role="primary"]
  840. ----
  841. http
  842. .authorizeRequests((authorize) -> authorize
  843. .filterSecurityInterceptorOncePerRequest(true)
  844. .mvcMatchers("/app/**").hasRole("APP")
  845. // ...
  846. .anyRequest().denyAll()
  847. )
  848. // ...
  849. ----
  850. Kotlin::
  851. +
  852. [source,kotlin,role="secondary"]
  853. ----
  854. http {
  855. authorizeRequests {
  856. filterSecurityInterceptorOncePerRequest = true
  857. authorize("/app/**", hasRole("APP"))
  858. // ...
  859. authorize(anyRequest, denyAll)
  860. }
  861. }
  862. ----
  863. Xml::
  864. +
  865. [source,xml,role="secondary"]
  866. ----
  867. <http once-per-request="true">
  868. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  869. <!-- ... -->
  870. <intercept-url pattern="/**" access="denyAll"/>
  871. </http>
  872. ----
  873. ======
  874. to:
  875. [tabs]
  876. ======
  877. Java::
  878. +
  879. [source,java,role="primary"]
  880. ----
  881. http
  882. .authorizeHttpRequests((authorize) -> authorize
  883. .shouldFilterAllDispatcherTypes(false)
  884. .mvcMatchers("/app/**").hasRole("APP")
  885. // ...
  886. .anyRequest().denyAll()
  887. )
  888. // ...
  889. ----
  890. Kotlin::
  891. +
  892. [source,kotlin,role="secondary"]
  893. ----
  894. http {
  895. authorizeHttpRequests {
  896. shouldFilterAllDispatcherTypes = false
  897. authorize("/app/**", hasRole("APP"))
  898. // ...
  899. authorize(anyRequest, denyAll)
  900. }
  901. }
  902. ----
  903. Xml::
  904. +
  905. [source,xml,role="secondary"]
  906. ----
  907. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  908. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  909. <!-- ... -->
  910. <intercept-url pattern="/**" access="denyAll"/>
  911. </http>
  912. ----
  913. ======
  914. === Migrate `hasIpAddress` to `access(AuthorizationManager)`
  915. `hasIpAddress` has no DSL equivalent in `authorizeHttpRequests`.
  916. As such, you need to change any called to `hasIpAddress` to using an `AuthorizationManager`.
  917. First, construct an `IpAddressMatcher` like so:
  918. ====
  919. .Java
  920. [source,java,role="primary"]
  921. ----
  922. IpAddressMatcher hasIpAddress = new IpAddressMatcher("127.0.0.1");
  923. ----
  924. ====
  925. And then change from this:
  926. ====
  927. .Java
  928. [source,java,role="primary"]
  929. ----
  930. http
  931. .authorizeRequests((authorize) -> authorize
  932. .mvcMatchers("/app/**").hasIpAddress("127.0.0.1")
  933. // ...
  934. .anyRequest().denyAll()
  935. )
  936. // ...
  937. ----
  938. ====
  939. to this:
  940. ====
  941. .Java
  942. [source,java,role="primary"]
  943. ----
  944. http
  945. .authorizeHttpRequests((authorize) -> authorize
  946. .requestMatchers("/app/**").access((authentication, context) ->
  947. new AuthorizationDecision(hasIpAddress.matches(context.getRequest()))
  948. // ...
  949. .anyRequest().denyAll()
  950. )
  951. // ...
  952. ----
  953. ====
  954. [NOTE]
  955. Securing by IP Address is quite fragile to begin with.
  956. For that reason, there are no plans to port this support over to `authorizeHttpRequests`.
  957. === Migrate SpEL expressions to `AuthorizationManager`
  958. For authorization rules, Java tends to be easier to test and maintain than SpEL.
  959. As such, `authorizeHttpRequests` does not have a method for declaring a `String` SpEL.
  960. Instead, you can implement your own `AuthorizationManager` implementation or use `WebExpressionAuthorizationManager`.
  961. For completeness, both options will be demonstrated.
  962. First, if you have the following SpEL:
  963. [tabs]
  964. ======
  965. Java::
  966. +
  967. [source,java,role="primary"]
  968. ----
  969. http
  970. .authorizeRequests((authorize) -> authorize
  971. .filterSecurityInterceptorOncePerRequest(true)
  972. .mvcMatchers("/complicated/**").access("hasRole('ADMIN') || hasAuthority('SCOPE_read')")
  973. // ...
  974. .anyRequest().denyAll()
  975. )
  976. // ...
  977. ----
  978. Kotlin::
  979. +
  980. [source,kotlin,role="secondary"]
  981. ----
  982. http {
  983. authorizeRequests {
  984. filterSecurityInterceptorOncePerRequest = true
  985. authorize("/complicated/**", access("hasRole('ADMIN') || hasAuthority('SCOPE_read')"))
  986. // ...
  987. authorize(anyRequest, denyAll)
  988. }
  989. }
  990. ----
  991. ======
  992. Then you can compose your own `AuthorizationManager` with Spring Security authorization primitives like so:
  993. [tabs]
  994. ======
  995. Java::
  996. +
  997. [source,java,role="primary"]
  998. ----
  999. http
  1000. .authorizeHttpRequests((authorize) -> authorize
  1001. .shouldFilterAllDispatcherTypes(false)
  1002. .mvcMatchers("/complicated/**").access(anyOf(hasRole("ADMIN"), hasAuthority("SCOPE_read"))
  1003. // ...
  1004. .anyRequest().denyAll()
  1005. )
  1006. // ...
  1007. ----
  1008. Kotlin::
  1009. +
  1010. [source,kotlin,role="secondary"]
  1011. ----
  1012. http {
  1013. authorizeHttpRequests {
  1014. shouldFilterAllDispatcherTypes = false
  1015. authorize("/complicated/**", access(anyOf(hasRole("ADMIN"), hasAuthority("SCOPE_read"))
  1016. // ...
  1017. authorize(anyRequest, denyAll)
  1018. }
  1019. }
  1020. ----
  1021. ======
  1022. Or you can use `WebExpressionAuthorizationManager` in the following way:
  1023. [tabs]
  1024. ======
  1025. Java::
  1026. +
  1027. [source,java,role="primary"]
  1028. ----
  1029. http
  1030. .authorizeRequests((authorize) -> authorize
  1031. .filterSecurityInterceptorOncePerRequest(true)
  1032. .mvcMatchers("/complicated/**").access(
  1033. new WebExpressionAuthorizationManager("hasRole('ADMIN') || hasAuthority('SCOPE_read')")
  1034. )
  1035. // ...
  1036. .anyRequest().denyAll()
  1037. )
  1038. // ...
  1039. ----
  1040. Kotlin::
  1041. +
  1042. [source,kotlin,role="secondary"]
  1043. ----
  1044. http {
  1045. authorizeRequests {
  1046. filterSecurityInterceptorOncePerRequest = true
  1047. authorize("/complicated/**", access(
  1048. WebExpressionAuthorizationManager("hasRole('ADMIN') || hasAuthority('SCOPE_read')"))
  1049. )
  1050. // ...
  1051. authorize(anyRequest, denyAll)
  1052. }
  1053. }
  1054. ----
  1055. ======
  1056. [[switch-filter-all-dispatcher-types]]
  1057. === Switch to filter all dispatcher types
  1058. Spring Security 5.8 and earlier only xref:servlet/authorization/architecture.adoc[perform authorization] once per request.
  1059. This means that dispatcher types like `FORWARD` and `INCLUDE` that run after `REQUEST` are not secured by default.
  1060. It's recommended that Spring Security secure all dispatch types.
  1061. As such, in 6.0, Spring Security changes this default.
  1062. So, finally, change your authorization rules to filter all dispatcher types.
  1063. To do this, you should change:
  1064. [tabs]
  1065. ======
  1066. Java::
  1067. +
  1068. [source,java,role="primary"]
  1069. ----
  1070. http
  1071. .authorizeHttpRequests((authorize) -> authorize
  1072. .shouldFilterAllDispatcherTypes(false)
  1073. .mvcMatchers("/app/**").hasRole("APP")
  1074. // ...
  1075. .anyRequest().denyAll()
  1076. )
  1077. // ...
  1078. ----
  1079. Kotlin::
  1080. +
  1081. [source,kotlin,role="secondary"]
  1082. ----
  1083. http {
  1084. authorizeHttpRequests {
  1085. shouldFilterAllDispatcherTypes = false
  1086. authorize("/app/**", hasRole("APP"))
  1087. // ...
  1088. authorize(anyRequest, denyAll)
  1089. }
  1090. }
  1091. ----
  1092. Xml::
  1093. +
  1094. [source,xml,role="secondary"]
  1095. ----
  1096. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  1097. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1098. <!-- ... -->
  1099. <intercept-url pattern="/**" access="denyAll"/>
  1100. </http>
  1101. ----
  1102. ======
  1103. to:
  1104. [tabs]
  1105. ======
  1106. Java::
  1107. +
  1108. [source,java,role="primary"]
  1109. ----
  1110. http
  1111. .authorizeHttpRequests((authorize) -> authorize
  1112. .shouldFilterAllDispatcherTypes(true)
  1113. .mvcMatchers("/app/**").hasRole("APP")
  1114. // ...
  1115. .anyRequest().denyAll()
  1116. )
  1117. // ...
  1118. ----
  1119. Kotlin::
  1120. +
  1121. [source,kotlin,role="secondary"]
  1122. ----
  1123. http {
  1124. authorizeHttpRequests {
  1125. shouldFilterAllDispatcherTypes = true
  1126. authorize("/app/**", hasRole("APP"))
  1127. // ...
  1128. authorize(anyRequest, denyAll)
  1129. }
  1130. }
  1131. ----
  1132. Xml::
  1133. +
  1134. [source,xml,role="secondary"]
  1135. ----
  1136. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  1137. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1138. <!-- ... -->
  1139. <intercept-url pattern="/**" access="denyAll"/>
  1140. </http>
  1141. ----
  1142. ======
  1143. And, the `FilterChainProxy` should be registered for all dispatcher types as well.
  1144. 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:
  1145. [tabs]
  1146. ======
  1147. application.properties::
  1148. +
  1149. [source,properties,role="primary"]
  1150. ----
  1151. spring.security.filter.dispatcher-types=request,async,error,forward,include
  1152. ----
  1153. ======
  1154. If you are xref:servlet/configuration/java.adoc#_abstractsecuritywebapplicationinitializer[using the `AbstractSecurityWebApplicationInitializer`] you should override the `getSecurityDispatcherTypes` method and return all dispatcher types:
  1155. [tabs]
  1156. ======
  1157. Java::
  1158. +
  1159. [source,java,role="primary"]
  1160. ----
  1161. import org.springframework.security.web.context.*;
  1162. public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
  1163. @Override
  1164. protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
  1165. return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC,
  1166. DispatcherType.FORWARD, DispatcherType.INCLUDE);
  1167. }
  1168. }
  1169. ----
  1170. ======
  1171. ==== Permit `FORWARD` when using Spring MVC
  1172. 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.
  1173. This is because when Spring MVC detects a mapping between view name and the actual views, it will perform a forward to the view.
  1174. As we saw on the <<switch-filter-all-dispatcher-types,previous section>>, Spring Security 6.0 will apply authorization to `FORWARD` requests by default.
  1175. Consider the following common configuration:
  1176. [tabs]
  1177. ======
  1178. Java::
  1179. +
  1180. [source,java,role="primary"]
  1181. ----
  1182. @Bean
  1183. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  1184. http
  1185. .authorizeHttpRequests((authorize) -> authorize
  1186. .shouldFilterAllDispatcherTypes(true)
  1187. .requestMatchers("/").authenticated()
  1188. .anyRequest().denyAll()
  1189. )
  1190. .formLogin((form) -> form
  1191. .loginPage("/login")
  1192. .permitAll()
  1193. ));
  1194. return http.build();
  1195. }
  1196. ----
  1197. ======
  1198. and one of the following equivalents MVC view mapping configurations:
  1199. [tabs]
  1200. ======
  1201. Java::
  1202. +
  1203. [source,java,role="primary"]
  1204. ----
  1205. @Controller
  1206. public class MyController {
  1207. @GetMapping("/login")
  1208. public String login() {
  1209. return "login";
  1210. }
  1211. }
  1212. ----
  1213. ======
  1214. [tabs]
  1215. ======
  1216. Java::
  1217. +
  1218. [source,java,role="primary"]
  1219. ----
  1220. @Configuration
  1221. public class MyWebMvcConfigurer implements WebMvcConfigurer {
  1222. @Override
  1223. public void addViewControllers(ViewControllerRegistry registry) {
  1224. registry.addViewController("/login").setViewName("login");
  1225. }
  1226. }
  1227. ----
  1228. ======
  1229. 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.
  1230. 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`.
  1231. To fix this, you should configure Spring Security to permit `FORWARD` requests:
  1232. [tabs]
  1233. ======
  1234. Java::
  1235. +
  1236. [source,java,role="primary"]
  1237. ----
  1238. http
  1239. .authorizeHttpRequests((authorize) -> authorize
  1240. .shouldFilterAllDispatcherTypes(true)
  1241. .dispatcherTypeMatchers(DispatcherType.FORWARD).permitAll()
  1242. .anyRequest().denyAll()
  1243. )
  1244. // ...
  1245. ----
  1246. Kotlin::
  1247. +
  1248. [source,kotlin,role="secondary"]
  1249. ----
  1250. http {
  1251. authorizeHttpRequests {
  1252. shouldFilterAllDispatcherTypes = true
  1253. authorize(DispatcherTypeRequestMatcher(DispatcherType.FORWARD), permitAll)
  1254. authorize(anyRequest, denyAll)
  1255. }
  1256. }
  1257. ----
  1258. Xml::
  1259. +
  1260. [source,xml,role="secondary"]
  1261. ----
  1262. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  1263. <intercept-url request-matcher-ref="forwardRequestMatcher" access="permitAll()" />
  1264. <!-- ... -->
  1265. <intercept-url pattern="/**" access="denyAll"/>
  1266. </http>
  1267. <bean name="forwardRequestMatcher" class="org.springframework.security.web.util.matcher.DispatcherTypeRequestMatcher">
  1268. <constructor-arg value="FORWARD"/>
  1269. </bean>
  1270. ----
  1271. ======
  1272. === Replace any custom filter-security ``AccessDecisionManager``s
  1273. 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.
  1274. The preparation strategy will depend on your reason for each arrangement.
  1275. Read on to find the best match for your situation.
  1276. ==== I use `UnanimousBased`
  1277. 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:
  1278. [tabs]
  1279. ======
  1280. Java::
  1281. +
  1282. [source,java,role="primary"]
  1283. ----
  1284. @Bean
  1285. AuthorizationManager<RequestAuthorizationContext> requestAuthorization() {
  1286. PolicyAuthorizationManager policy = ...;
  1287. LocalAuthorizationManager local = ...;
  1288. return AuthorizationManagers.allOf(policy, local);
  1289. }
  1290. ----
  1291. Kotlin::
  1292. +
  1293. [source,kotlin,role="secondary"]
  1294. ----
  1295. @Bean
  1296. fun requestAuthorization(): AuthorizationManager<RequestAuthorizationContext> {
  1297. val policy: PolicyAuthorizationManager = ...
  1298. val local: LocalAuthorizationManager = ...
  1299. return AuthorizationManagers.allOf(policy, local)
  1300. }
  1301. ----
  1302. Xml::
  1303. +
  1304. [source,xml,role="secondary"]
  1305. ----
  1306. <bean id="requestAuthorization" class="org.springframework.security.authorization.AuthorizationManagers"
  1307. factory-method="allOf">
  1308. <constructor-arg>
  1309. <util:list>
  1310. <bean class="my.PolicyAuthorizationManager"/>
  1311. <bean class="my.LocalAuthorizationManager"/>
  1312. </util:list>
  1313. </constructor-arg>
  1314. </bean>
  1315. ----
  1316. ======
  1317. then, wire it into the DSL like so:
  1318. [tabs]
  1319. ======
  1320. Java::
  1321. +
  1322. [source,java,role="primary"]
  1323. ----
  1324. http
  1325. .authorizeHttpRequests((authorize) -> authorize.anyRequest().access(requestAuthorization))
  1326. // ...
  1327. ----
  1328. Kotlin::
  1329. +
  1330. [source,kotlin,role="secondary"]
  1331. ----
  1332. http {
  1333. authorizeHttpRequests {
  1334. authorize(anyRequest, requestAuthorization)
  1335. }
  1336. // ...
  1337. }
  1338. ----
  1339. Xml::
  1340. +
  1341. [source,xml,role="secondary"]
  1342. ----
  1343. <http authorization-manager-ref="requestAuthorization"/>
  1344. ----
  1345. ======
  1346. [NOTE]
  1347. ====
  1348. `authorizeHttpRequests` is designed so that you can apply a custom `AuthorizationManager` to any url pattern.
  1349. See xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[the reference] for more details.
  1350. ====
  1351. ==== I use `AffirmativeBased`
  1352. 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:
  1353. [tabs]
  1354. ======
  1355. Java::
  1356. +
  1357. [source,java,role="primary"]
  1358. ----
  1359. @Bean
  1360. AuthorizationManager<RequestAuthorizationContext> requestAuthorization() {
  1361. PolicyAuthorizationManager policy = ...;
  1362. LocalAuthorizationManager local = ...;
  1363. return AuthorizationManagers.anyOf(policy, local);
  1364. }
  1365. ----
  1366. Kotlin::
  1367. +
  1368. [source,kotlin,role="secondary"]
  1369. ----
  1370. @Bean
  1371. fun requestAuthorization(): AuthorizationManager<RequestAuthorizationContext> {
  1372. val policy: PolicyAuthorizationManager = ...
  1373. val local: LocalAuthorizationManager = ...
  1374. return AuthorizationManagers.anyOf(policy, local)
  1375. }
  1376. ----
  1377. Xml::
  1378. +
  1379. [source,xml,role="secondary"]
  1380. ----
  1381. <bean id="requestAuthorization" class="org.springframework.security.authorization.AuthorizationManagers"
  1382. factory-method="anyOf">
  1383. <constructor-arg>
  1384. <util:list>
  1385. <bean class="my.PolicyAuthorizationManager"/>
  1386. <bean class="my.LocalAuthorizationManager"/>
  1387. </util:list>
  1388. </constructor-arg>
  1389. </bean>
  1390. ----
  1391. ======
  1392. then, wire it into the DSL like so:
  1393. [tabs]
  1394. ======
  1395. Java::
  1396. +
  1397. [source,java,role="primary"]
  1398. ----
  1399. http
  1400. .authorizeHttpRequests((authorize) -> authorize.anyRequest().access(requestAuthorization))
  1401. // ...
  1402. ----
  1403. Kotlin::
  1404. +
  1405. [source,kotlin,role="secondary"]
  1406. ----
  1407. http {
  1408. authorizeHttpRequests {
  1409. authorize(anyRequest, requestAuthorization)
  1410. }
  1411. // ...
  1412. }
  1413. ----
  1414. Xml::
  1415. +
  1416. [source,xml,role="secondary"]
  1417. ----
  1418. <http authorization-manager-ref="requestAuthorization"/>
  1419. ----
  1420. ======
  1421. [NOTE]
  1422. ====
  1423. `authorizeHttpRequests` is designed so that you can apply a custom `AuthorizationManager` to any url pattern.
  1424. See xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[the reference] for more details.
  1425. ====
  1426. ==== I use `ConsensusBased`
  1427. There is no framework-provided equivalent for {security-api-url}org/springframework/security/access/vote/ConsensusBased.html[`ConsensusBased`].
  1428. 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.
  1429. 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`].
  1430. ==== I use a custom `AccessDecisionVoter`
  1431. You should either change the class to implement {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] or create an adapter.
  1432. Without knowing what your custom voter is doing, it is impossible to recommend a general-purpose solution.
  1433. 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:
  1434. [tabs]
  1435. ======
  1436. Java::
  1437. +
  1438. [source,java,role="primary"]
  1439. ----
  1440. public final class AnyRequestAuthenticatedAuthorizationManagerAdapter implements AuthorizationManager<RequestAuthorizationContext> {
  1441. private final SecurityMetadataSource metadata;
  1442. private final AccessDecisionVoter voter;
  1443. public PreAuthorizeAuthorizationManagerAdapter(SecurityExpressionHandler expressionHandler) {
  1444. Map<RequestMatcher, List<ConfigAttribute>> requestMap = Collections.singletonMap(
  1445. AnyRequestMatcher.INSTANCE, Collections.singletonList(new SecurityConfig("authenticated")));
  1446. this.metadata = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
  1447. WebExpressionVoter voter = new WebExpressionVoter();
  1448. voter.setExpressionHandler(expressionHandler);
  1449. this.voter = voter;
  1450. }
  1451. public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
  1452. List<ConfigAttribute> attributes = this.metadata.getAttributes(context);
  1453. int decision = this.voter.vote(authentication.get(), invocation, attributes);
  1454. if (decision == ACCESS_GRANTED) {
  1455. return new AuthorizationDecision(true);
  1456. }
  1457. if (decision == ACCESS_DENIED) {
  1458. return new AuthorizationDecision(false);
  1459. }
  1460. return null; // abstain
  1461. }
  1462. }
  1463. ----
  1464. ======
  1465. 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`].
  1466. [[replace-hasrole-hasauthority]]
  1467. === Replace `hasRole` with `hasAuthority` if using `GrantedAuthorityDefaults`
  1468. Currently, the `hasRole` method inside `authorizeHttpRequests` does not support the `GrantedAuthorityDefaults` bean like the `authorizeRequests` does.
  1469. Therefore, if you are using `GrantedAuthorityDefaults` to change the prefix of your roles, you will need to use `hasAuthority` instead of `hasRole`.
  1470. For example, you will have to change from:
  1471. .authorizeRequests with custom role prefix
  1472. [source,java]
  1473. ----
  1474. @Bean
  1475. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  1476. http
  1477. .authorizeRequests((authorize) -> authorize
  1478. .anyRequest().hasRole("ADMIN")
  1479. );
  1480. return http.build();
  1481. }
  1482. @Bean
  1483. public GrantedAuthorityDefaults grantedAuthorityDefaults() {
  1484. return new GrantedAuthorityDefaults("MYPREFIX_");
  1485. }
  1486. ----
  1487. to:
  1488. .authorizeHttpRequests with hasAuthority and custom role prefix
  1489. [source,java]
  1490. ----
  1491. @Bean
  1492. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  1493. http
  1494. .authorizeHttpRequests((authorize) -> authorize
  1495. .anyRequest().hasAuthority("MYPREFIX_ADMIN")
  1496. );
  1497. return http.build();
  1498. }
  1499. ----
  1500. This should be supported in the future, see https://github.com/spring-projects/spring-security/issues/13215[gh-13227] for more details.
  1501. [[servlet-authorizationmanager-requests-opt-out]]
  1502. === Opt-out Steps
  1503. In case you had trouble, take a look at these scenarios for optimal opt out behavior:
  1504. ==== I cannot secure all dispatcher types
  1505. If you cannot secure all dispatcher types, first try and declare which dispatcher types should not require authorization like so:
  1506. [tabs]
  1507. ======
  1508. Java::
  1509. +
  1510. [source,java,role="primary"]
  1511. ----
  1512. http
  1513. .authorizeHttpRequests((authorize) -> authorize
  1514. .shouldFilterAllDispatcherTypes(true)
  1515. .dispatcherTypeMatchers(FORWARD, INCLUDE).permitAll()
  1516. .mvcMatchers("/app/**").hasRole("APP")
  1517. // ...
  1518. .anyRequest().denyAll()
  1519. )
  1520. // ...
  1521. ----
  1522. Kotlin::
  1523. +
  1524. [source,kotlin,role="secondary"]
  1525. ----
  1526. http {
  1527. authorizeHttpRequests {
  1528. shouldFilterAllDispatcherTypes = true
  1529. authorize(DispatcherTypeRequestMatcher(FORWARD, INCLUDE), permitAll)
  1530. authorize("/app/**", hasRole("APP"))
  1531. // ...
  1532. authorize(anyRequest, denyAll)
  1533. }
  1534. }
  1535. ----
  1536. Xml::
  1537. +
  1538. [source,xml,role="secondary"]
  1539. ----
  1540. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  1541. <intercept-url request-matcher-ref="dispatchers"/>
  1542. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1543. <!-- ... -->
  1544. <intercept-url pattern="/**" access="denyAll"/>
  1545. </http>
  1546. <bean id="dispatchers" class="org.springframework.security.web.util.matcher.DispatcherTypeRequestMatcher">
  1547. <constructor-arg>
  1548. <util:list value-type="javax.servlet.DispatcherType">
  1549. <value>FORWARD</value>
  1550. <value>INCLUDE</value>
  1551. </util:list>
  1552. </constructor-arg>
  1553. </bean>
  1554. ----
  1555. ======
  1556. 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`:
  1557. [tabs]
  1558. ======
  1559. Java::
  1560. +
  1561. [source,java,role="primary"]
  1562. ----
  1563. http
  1564. .authorizeHttpRequests((authorize) -> authorize
  1565. .filterAllDispatcherTypes(false)
  1566. .mvcMatchers("/app/**").hasRole("APP")
  1567. // ...
  1568. )
  1569. // ...
  1570. ----
  1571. Kotlin::
  1572. +
  1573. [source,kotlin,role="secondary"]
  1574. ----
  1575. http {
  1576. authorizeHttpRequests {
  1577. filterAllDispatcherTypes = false
  1578. authorize("/messages/**", hasRole("APP"))
  1579. // ...
  1580. }
  1581. }
  1582. ----
  1583. Xml::
  1584. +
  1585. [source,xml,role="secondary"]
  1586. ----
  1587. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  1588. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1589. <!-- ... -->
  1590. </http>
  1591. ----
  1592. ======
  1593. or, if you are still using `authorizeRequests` or `use-authorization-manager="false"`, set `oncePerRequest` to `true`:
  1594. [tabs]
  1595. ======
  1596. Java::
  1597. +
  1598. [source,java,role="primary"]
  1599. ----
  1600. http
  1601. .authorizeRequests((authorize) -> authorize
  1602. .filterSecurityInterceptorOncePerRequest(true)
  1603. .mvcMatchers("/app/**").hasRole("APP")
  1604. // ...
  1605. )
  1606. // ...
  1607. ----
  1608. Kotlin::
  1609. +
  1610. [source,kotlin,role="secondary"]
  1611. ----
  1612. http {
  1613. authorizeRequests {
  1614. filterSecurityInterceptorOncePerRequest = true
  1615. authorize("/messages/**", hasRole("APP"))
  1616. // ...
  1617. }
  1618. }
  1619. ----
  1620. Xml::
  1621. +
  1622. [source,xml,role="secondary"]
  1623. ----
  1624. <http once-per-request="true" use-authorization-manager="false">
  1625. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1626. <!-- ... -->
  1627. </http>
  1628. ----
  1629. ======
  1630. ==== I cannot declare an authorization rule for all requests
  1631. 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:
  1632. [tabs]
  1633. ======
  1634. Java::
  1635. +
  1636. [source,java,role="primary"]
  1637. ----
  1638. http
  1639. .authorizeHttpReqeusts((authorize) -> authorize
  1640. .mvcMatchers("/app/*").hasRole("APP")
  1641. // ...
  1642. .anyRequest().permitAll()
  1643. )
  1644. ----
  1645. Kotlin::
  1646. +
  1647. [source,kotlin,role="secondary"]
  1648. ----
  1649. http {
  1650. authorizeHttpRequests {
  1651. authorize("/app*", hasRole("APP"))
  1652. // ...
  1653. authorize(anyRequest, permitAll)
  1654. }
  1655. }
  1656. ----
  1657. Xml::
  1658. +
  1659. [source,xml,role="secondary"]
  1660. ----
  1661. <http>
  1662. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1663. <!-- ... -->
  1664. <intercept-url pattern="/**" access="permitAll"/>
  1665. </http>
  1666. ----
  1667. ======
  1668. ==== I cannot migrate my SpEL or my `AccessDecisionManager`
  1669. 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.
  1670. 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.
  1671. Second, if you still need your custom `access-decision-manager-ref` or have some other reason to opt out of `AuthorizationManager`, do:
  1672. .Xml
  1673. [source,xml,role="secondary"]
  1674. ----
  1675. <http use-authorization-manager="false">
  1676. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1677. <!-- ... -->
  1678. </http>
  1679. ----