authorization.adoc 53 KB

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