authorization.adoc 49 KB

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