migration.adoc 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. [[migration]]
  2. = Migrating to 6.0
  3. The Spring Security team has prepared the 5.8 release to simplify upgrading to Spring Security 6.0.
  4. Use 5.8 and the steps below to minimize changes when
  5. ifdef::spring-security-version[]
  6. xref:6.0.0@migration.adoc[updating to 6.0]
  7. endif::[]
  8. ifndef::spring-security-version[]
  9. updating to 6.0
  10. endif::[]
  11. .
  12. == Servlet
  13. === Defer Loading CsrfToken
  14. In Spring Security 5, the default behavior is that the `CsrfToken` will be loaded on every request.
  15. This means that in a typical setup, the `HttpSession` must be read for every request even if it is unnecessary.
  16. In Spring Security 6, the default is that the lookup of the `CsrfToken` will be deferred until it is needed.
  17. To opt into the new Spring Security 6 default, the following configuration can be used.
  18. .Defer Loading `CsrfToken`
  19. ====
  20. .Java
  21. [source,java,role="primary"]
  22. ----
  23. @Bean
  24. DefaultSecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
  25. CsrfTokenRequestAttributeHandler requestHandler = new CsrfTokenRequestAttributeHandler();
  26. // set the name of the attribute the CsrfToken will be populated on
  27. requestHandler.setCsrfRequestAttributeName("_csrf");
  28. http
  29. // ...
  30. .csrf((csrf) -> csrf
  31. .csrfTokenRequestHandler(requestHandler)
  32. );
  33. return http.build();
  34. }
  35. ----
  36. .Kotlin
  37. [source,kotlin,role="secondary"]
  38. ----
  39. @Bean
  40. open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
  41. val requestHandler = CsrfTokenRequestAttributeHandler()
  42. // set the name of the attribute the CsrfToken will be populated on
  43. requestHandler.setCsrfRequestAttributeName("_csrf")
  44. http {
  45. csrf {
  46. csrfTokenRequestHandler = requestHandler
  47. }
  48. }
  49. return http.build()
  50. }
  51. ----
  52. .XML
  53. [source,xml,role="secondary"]
  54. ----
  55. <http>
  56. <!-- ... -->
  57. <csrf request-handler-ref="requestHandler"/>
  58. </http>
  59. <b:bean id="requestHandler"
  60. class="org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler"
  61. p:csrfRequestAttributeName="_csrf"/>
  62. ----
  63. ====
  64. === Explicit Save SecurityContextRepository
  65. In Spring Security 5, the default behavior is for the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontext[`SecurityContext`] to automatically be saved to the xref:servlet/authentication/persistence.adoc#securitycontextrepository[`SecurityContextRepository`] using the xref:servlet/authentication/persistence.adoc#securitycontextpersistencefilter[`SecurityContextPersistenceFilter`].
  66. Saving must be done just prior to the `HttpServletResponse` being committed and just before `SecurityContextPersistenceFilter`.
  67. Unfortunately, automatic persistence of the `SecurityContext` can surprise users when it is done prior to the request completing (i.e. just prior to committing the `HttpServletResponse`).
  68. It also is complex to keep track of the state to determine if a save is necessary causing unnecessary writes to the `SecurityContextRepository` (i.e. `HttpSession`) at times.
  69. In Spring Security 6, the default behavior is that the xref:servlet/authentication/persistence.adoc#securitycontextholderfilter[`SecurityContextHolderFilter`] will only read the `SecurityContext` from `SecurityContextRepository` and populate it in the `SecurityContextHolder`.
  70. Users now must explicitly save the `SecurityContext` with the `SecurityContextRepository` if they want the `SecurityContext` to persist between requests.
  71. This removes ambiguity and improves performance by only requiring writing to the `SecurityContextRepository` (i.e. `HttpSession`) when it is necessary.
  72. To opt into the new Spring Security 6 default, the following configuration can be used.
  73. include::partial$servlet/architecture/security-context-explicit.adoc[]
  74. [[requestcache-query-optimization]]
  75. === Optimize Querying of `RequestCache`
  76. In Spring Security 5, the default behavior is to query the xref:servlet/architecture.adoc#savedrequests[saved request] on every request.
  77. This means that in a typical setup, that in order to use the xref:servlet/architecture.adoc#requestcache[`RequestCache`] the `HttpSession` is queried on every request.
  78. In Spring Security 6, the default is that `RequestCache` will only be queried for a cached request if the HTTP parameter `continue` is defined.
  79. This allows Spring Security to avoid unnecessarily reading the `HttpSession` with the `RequestCache`.
  80. In Spring Security 5 the default is to use `HttpSessionRequestCache` which will be queried for a cached request on every request.
  81. If you are not overriding the defaults (i.e. using `NullRequestCache`), then the following configuration can be used to explicitly opt into the Spring Security 6 behavior in Spring Security 5.8:
  82. include::partial$servlet/architecture/request-cache-continue.adoc[]
  83. === Use `AuthorizationManager` for Method Security
  84. 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.
  85. 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.
  86. '''
  87. [[servlet-replace-globalmethodsecurity-with-methodsecurity]]
  88. ==== 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]
  89. {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.
  90. 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.
  91. This means that the following two listings are functionally equivalent:
  92. ====
  93. .Java
  94. [source,java,role="primary"]
  95. ----
  96. @EnableGlobalMethodSecurity(prePostEnabled = true)
  97. ----
  98. .Kotlin
  99. [source,kotlin,role="secondary"]
  100. ----
  101. @EnableGlobalMethodSecurity(prePostEnabled = true)
  102. ----
  103. .Xml
  104. [source,xml,role="secondary"]
  105. ----
  106. <global-method-security pre-post-enabled="true"/>
  107. ----
  108. ====
  109. and:
  110. ====
  111. .Java
  112. [source,java,role="primary"]
  113. ----
  114. @EnableMethodSecurity
  115. ----
  116. .Kotlin
  117. [source,kotlin,role="secondary"]
  118. ----
  119. @EnableMethodSecurity
  120. ----
  121. .Xml
  122. [source,xml,role="secondary"]
  123. ----
  124. <method-security/>
  125. ----
  126. ====
  127. For applications not using the pre-post annotations, make sure to turn it off to avoid activating unwanted behavior.
  128. For example, a listing like:
  129. ====
  130. .Java
  131. [source,java,role="primary"]
  132. ----
  133. @EnableGlobalMethodSecurity(securedEnabled = true)
  134. ----
  135. .Kotlin
  136. [source,kotlin,role="secondary"]
  137. ----
  138. @EnableGlobalMethodSecurity(securedEnabled = true)
  139. ----
  140. .Xml
  141. [source,xml,role="secondary"]
  142. ----
  143. <global-method-security secured-enabled="true"/>
  144. ----
  145. ====
  146. should change to:
  147. ====
  148. .Java
  149. [source,java,role="primary"]
  150. ----
  151. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  152. ----
  153. .Kotlin
  154. [source,kotlin,role="secondary"]
  155. ----
  156. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  157. ----
  158. .Xml
  159. [source,xml,role="secondary"]
  160. ----
  161. <method-security secured-enabled="true" pre-post-enabled="false"/>
  162. ----
  163. ====
  164. '''
  165. [[servlet-replace-permissionevaluator-bean-with-methodsecurityexpression-handler]]
  166. ==== Publish a `MethodSecurityExpressionHandler` instead of a `PermissionEvaluator`
  167. `@EnableMethodSecurity` does not pick up a `PermissionEvaluator`.
  168. This helps keep its API simple.
  169. If you have a custom {security-api-url}org/springframework/security/access/PermissionEvaluator.html[`PermissionEvaluator`] `@Bean`, please change it from:
  170. ====
  171. .Java
  172. [source,java,role="primary"]
  173. ----
  174. @Bean
  175. static PermissionEvaluator permissionEvaluator() {
  176. // ... your evaluator
  177. }
  178. ----
  179. .Kotlin
  180. [source,kotlin,role="secondary"]
  181. ----
  182. companion object {
  183. @Bean
  184. fun permissionEvaluator(): PermissionEvaluator {
  185. // ... your evaluator
  186. }
  187. }
  188. ----
  189. ====
  190. to:
  191. ====
  192. .Java
  193. [source,java,role="primary"]
  194. ----
  195. @Bean
  196. static MethodSecurityExpressionHandler expressionHandler() {
  197. var expressionHandler = new DefaultMethodSecurityExpressionHandler();
  198. expressionHandler.setPermissionEvaluator(myPermissionEvaluator);
  199. return expressionHandler;
  200. }
  201. ----
  202. .Kotlin
  203. [source,kotlin,role="secondary"]
  204. ----
  205. companion object {
  206. @Bean
  207. fun expressionHandler(): MethodSecurityExpressionHandler {
  208. val expressionHandler = DefaultMethodSecurityExpressionHandler
  209. expressionHandler.setPermissionEvaluator(myPermissionEvaluator)
  210. return expressionHandler
  211. }
  212. }
  213. ----
  214. ====
  215. '''
  216. [[servlet-check-for-annotationconfigurationexceptions]]
  217. ==== Check for ``AnnotationConfigurationException``s
  218. `@EnableMethodSecurity` and `<method-security>` activate stricter enforcement of Spring Security's non-repeatable or otherwise incompatible annotations.
  219. 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.
  220. === Use `AuthorizationManager` for Message Security
  221. 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.
  222. 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.
  223. ==== Ensure all messages have defined authorization rules
  224. The now-deprecated {security-api-url}org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurer.html[message security support] permits all messages by default.
  225. xref:servlet/integrations/websocket.adoc[The new support] has the stronger default of denying all messages.
  226. To prepare for this, ensure that authorization rules exist are declared for every request.
  227. For example, an application configuration like:
  228. ====
  229. .Java
  230. [source,java,role="primary"]
  231. ----
  232. @Override
  233. protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
  234. messages
  235. .simpDestMatchers("/user/queue/errors").permitAll()
  236. .simpDestMatchers("/admin/**").hasRole("ADMIN");
  237. }
  238. ----
  239. .Kotlin
  240. [source,kotlin,role="secondary"]
  241. ----
  242. override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
  243. messages
  244. .simpDestMatchers("/user/queue/errors").permitAll()
  245. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  246. }
  247. ----
  248. .Xml
  249. [source,xml,role="secondary"]
  250. ----
  251. <websocket-message-broker>
  252. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  253. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  254. </websocket-message-broker>
  255. ----
  256. ====
  257. should change to:
  258. ====
  259. .Java
  260. [source,java,role="primary"]
  261. ----
  262. @Override
  263. protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
  264. messages
  265. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  266. .simpDestMatchers("/user/queue/errors").permitAll()
  267. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  268. .anyMessage().denyAll();
  269. }
  270. ----
  271. .Kotlin
  272. [source,kotlin,role="secondary"]
  273. ----
  274. override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
  275. messages
  276. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  277. .simpDestMatchers("/user/queue/errors").permitAll()
  278. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  279. .anyMessage().denyAll()
  280. }
  281. ----
  282. .Xml
  283. [source,xml,role="secondary"]
  284. ----
  285. <websocket-message-broker>
  286. <intercept-message type="CONNECT" access="permitAll"/>
  287. <intercept-message type="DISCONNECT" access="permitAll"/>
  288. <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
  289. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  290. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  291. <intercept-message pattern="/**" access="denyAll"/>
  292. </websocket-message-broker>
  293. ----
  294. ====
  295. ==== Add `@EnableWebSocketSecurity`
  296. [NOTE]
  297. ====
  298. If you want to have CSRF disabled and you are using Java configuration, the migration steps are slightly different.
  299. Instead of using `@EnableWebSocketSecurity`, you will override the appropriate methods in `WebSocketMessageBrokerConfigurer` yourself.
  300. Please see xref:servlet/integrations/websocket.adoc#websocket-sameorigin-disable[the reference manual] for details about this step.
  301. ====
  302. If you are using Java Configuration, add {security-api-url}org/springframework/security/config/annotation/web/socket/EnableWebSocketSecurity.html[`@EnableWebSocketSecurity`] to your application.
  303. For example, you can add it to your websocket security configuration class, like so:
  304. ====
  305. .Java
  306. [source,java,role="primary"]
  307. ----
  308. @EnableWebSocketSecurity
  309. @Configuration
  310. public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
  311. // ...
  312. }
  313. ----
  314. .Kotlin
  315. [source,kotlin,role="secondary"]
  316. ----
  317. @EnableWebSocketSecurity
  318. @Configuration
  319. class WebSocketSecurityConfig: AbstractSecurityWebSocketMessageBrokerConfigurer() {
  320. // ...
  321. }
  322. ----
  323. ====
  324. This will make a prototype instance of `MessageMatcherDelegatingAuthorizationManager.Builder` available to encourage configuration by composition instead of extension.
  325. ==== Use an `AuthorizationManager<Message<?>>` instance
  326. To start using `AuthorizationManager`, you can set the `use-authorization-manager` attribute in XML or you can publish an `AuthorizationManager<Message<?>>` `@Bean` in Java.
  327. For example, the following application configuration:
  328. ====
  329. .Java
  330. [source,java,role="primary"]
  331. ----
  332. @Override
  333. protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
  334. messages
  335. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  336. .simpDestMatchers("/user/queue/errors").permitAll()
  337. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  338. .anyMessage().denyAll();
  339. }
  340. ----
  341. .Kotlin
  342. [source,kotlin,role="secondary"]
  343. ----
  344. override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
  345. messages
  346. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  347. .simpDestMatchers("/user/queue/errors").permitAll()
  348. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  349. .anyMessage().denyAll()
  350. }
  351. ----
  352. .Xml
  353. [source,xml,role="secondary"]
  354. ----
  355. <websocket-message-broker>
  356. <intercept-message type="CONNECT" access="permitAll"/>
  357. <intercept-message type="DISCONNECT" access="permitAll"/>
  358. <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
  359. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  360. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  361. <intercept-message pattern="/**" access="denyAll"/>
  362. </websocket-message-broker>
  363. ----
  364. ====
  365. changes to:
  366. ====
  367. .Java
  368. [source,java,role="primary"]
  369. ----
  370. @Bean
  371. AuthorizationManager<Message<?>> messageSecurity(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
  372. messages
  373. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  374. .simpDestMatchers("/user/queue/errors").permitAll()
  375. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  376. .anyMessage().denyAll();
  377. return messages.build();
  378. }
  379. ----
  380. .Kotlin
  381. [source,kotlin,role="secondary"]
  382. ----
  383. @Bean
  384. fun messageSecurity(val messages: MessageMatcherDelegatingAuthorizationManager.Builder): AuthorizationManager<Message<?>> {
  385. messages
  386. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  387. .simpDestMatchers("/user/queue/errors").permitAll()
  388. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  389. .anyMessage().denyAll()
  390. return messages.build()
  391. }
  392. ----
  393. .Xml
  394. [source,xml,role="secondary"]
  395. ----
  396. <websocket-message-broker use-authorization-manager="true">
  397. <intercept-message type="CONNECT" access="permitAll"/>
  398. <intercept-message type="DISCONNECT" access="permitAll"/>
  399. <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
  400. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  401. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  402. <intercept-message pattern="/**" access="denyAll"/>
  403. </websocket-message-broker>
  404. ----
  405. ====
  406. ==== Stop Implementing `AbstractSecurityWebSocketMessageBrokerConfigurer`
  407. If you are using Java configuration, you can now simply extend `WebSocketMessageBrokerConfigurer`.
  408. For example, if your class that extends `AbstractSecurityWebSocketMessageBrokerConfigurer` is called `WebSocketSecurityConfig`, then:
  409. ====
  410. .Java
  411. [source,java,role="primary"]
  412. ----
  413. @EnableWebSocketSecurity
  414. @Configuration
  415. public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
  416. // ...
  417. }
  418. ----
  419. .Kotlin
  420. [source,kotlin,role="secondary"]
  421. ----
  422. @EnableWebSocketSecurity
  423. @Configuration
  424. class WebSocketSecurityConfig: AbstractSecurityWebSocketMessageBrokerConfigurer() {
  425. // ...
  426. }
  427. ----
  428. ====
  429. changes to:
  430. ====
  431. .Java
  432. [source,java,role="primary"]
  433. ----
  434. @EnableWebSocketSecurity
  435. @Configuration
  436. public class WebSocketSecurityConfig implements WebSocketMessageBrokerConfigurer {
  437. // ...
  438. }
  439. ----
  440. .Kotlin
  441. [source,kotlin,role="secondary"]
  442. ----
  443. @EnableWebSocketSecurity
  444. @Configuration
  445. class WebSocketSecurityConfig: WebSocketMessageBrokerConfigurer {
  446. // ...
  447. }
  448. ----
  449. ====
  450. [[servlet-authorizationmanager-messages-opt-out]]
  451. ==== Opt-out Steps
  452. In case you had trouble, take a look at these scenarios for optimal opt out behavior:
  453. ===== I cannot declare an authorization rule for all requests
  454. 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:
  455. ====
  456. .Java
  457. [source,java,role="primary"]
  458. ----
  459. @Bean
  460. AuthorizationManager<Message<?>> messageSecurity(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
  461. messages
  462. .simpDestMatchers("/user/queue/errors").permitAll()
  463. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  464. // ...
  465. .anyMessage().permitAll();
  466. return messages.build();
  467. }
  468. ----
  469. .Kotlin
  470. [source,kotlin,role="secondary"]
  471. ----
  472. @Bean
  473. fun messageSecurity(val messages: MessageMatcherDelegatingAuthorizationManager.Builder): AuthorizationManager<Message<?>> {
  474. messages
  475. .simpDestMatchers("/user/queue/errors").permitAll()
  476. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  477. // ...
  478. .anyMessage().permitAll();
  479. return messages.build()
  480. }
  481. ----
  482. .Xml
  483. [source,xml,role="secondary"]
  484. ----
  485. <websocket-message-broker use-authorization-manager="true">
  486. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  487. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  488. <!-- ... -->
  489. <intercept-message pattern="/**" access="permitAll"/>
  490. </websocket-message-broker>
  491. ----
  492. ====
  493. ===== I cannot get CSRF working, need some other `AbstractSecurityWebSocketMessageBrokerConfigurer` feature, or am having trouble with `AuthorizationManager`
  494. In the case of Java, you may continue using `AbstractMessageSecurityWebSocketMessageBrokerConfigurer`.
  495. Even though it is deprecated, it will not be removed in 6.0.
  496. In the case of XML, you can opt out of `AuthorizationManager` by setting `use-authorization-manager="false"`:
  497. ====
  498. .Xml
  499. [source,xml,role="secondary"]
  500. ----
  501. <websocket-message-broker>
  502. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  503. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  504. </websocket-message-broker>
  505. ----
  506. ====
  507. to:
  508. ====
  509. .Xml
  510. [source,xml,role="secondary"]
  511. ----
  512. <websocket-message-broker use-authorization-manager="false">
  513. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  514. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  515. </websocket-message-broker>
  516. ----
  517. ====
  518. === Use `AuthorizationManager` for Request Security
  519. 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].
  520. 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.
  521. ==== Ensure that all requests have defined authorization rules
  522. In Spring Security 5.8 and earlier, requests with no authorization rule are permitted by default.
  523. It is a stronger security position to deny by default, thus requiring that authorization rules be clearly defined for every endpoint.
  524. As such, in 6.0, Spring Security by default denies any request that is missing an authorization rule.
  525. 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.
  526. 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.
  527. [NOTE]
  528. ====
  529. You may already have an `anyRequest` rule defined that you are happy with in which case this step can be skipped.
  530. ====
  531. Adding `denyAll` to the end looks like changing:
  532. ====
  533. .Java
  534. [source,java,role="primary"]
  535. ----
  536. http
  537. .authorizeRequests((authorize) -> authorize
  538. .filterSecurityInterceptorOncePerRequest(true)
  539. .mvcMatchers("/app/**").hasRole("APP")
  540. // ...
  541. )
  542. // ...
  543. ----
  544. .Kotlin
  545. [source,kotlin,role="secondary"]
  546. ----
  547. http {
  548. authorizeRequests {
  549. filterSecurityInterceptorOncePerRequest = true
  550. authorize("/app/**", hasRole("APP"))
  551. // ...
  552. }
  553. }
  554. ----
  555. .Xml
  556. [source,xml,role="secondary"]
  557. ----
  558. <http once-per-request="true">
  559. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  560. <!-- ... -->
  561. </http>
  562. ----
  563. ====
  564. to:
  565. ====
  566. .Java
  567. [source,java,role="primary"]
  568. ----
  569. http
  570. .authorizeRequests((authorize) -> authorize
  571. .filterSecurityInterceptorOncePerRequest(true)
  572. .mvcMatchers("/app/**").hasRole("APP")
  573. // ...
  574. .anyRequest().denyAll()
  575. )
  576. // ...
  577. ----
  578. .Kotlin
  579. [source,kotlin,role="secondary"]
  580. ----
  581. http {
  582. authorizeRequests {
  583. filterSecurityInterceptorOncePerRequest = true
  584. authorize("/app/**", hasRole("APP"))
  585. // ...
  586. authorize(anyRequest, denyAll)
  587. }
  588. }
  589. ----
  590. .Xml
  591. [source,xml,role="secondary"]
  592. ----
  593. <http once-per-request="true">
  594. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  595. <!-- ... -->
  596. <intercept-url pattern="/**" access="denyAll"/>
  597. </http>
  598. ----
  599. ====
  600. If you have already migrated to `authorizeHttpRequests`, the recommended change is the same.
  601. ==== Switch to `AuthorizationManager`
  602. 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.
  603. Change:
  604. ====
  605. .Java
  606. [source,java,role="primary"]
  607. ----
  608. http
  609. .authorizeRequests((authorize) -> authorize
  610. .filterSecurityInterceptorOncePerRequest(true)
  611. .mvcMatchers("/app/**").hasRole("APP")
  612. // ...
  613. .anyRequest().denyAll()
  614. )
  615. // ...
  616. ----
  617. .Kotlin
  618. [source,kotlin,role="secondary"]
  619. ----
  620. http {
  621. authorizeRequests {
  622. filterSecurityInterceptorOncePerRequest = true
  623. authorize("/app/**", hasRole("APP"))
  624. // ...
  625. authorize(anyRequest, denyAll)
  626. }
  627. }
  628. ----
  629. .Xml
  630. [source,xml,role="secondary"]
  631. ----
  632. <http once-per-request="true">
  633. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  634. <!-- ... -->
  635. <intercept-url pattern="/**" access="denyAll"/>
  636. </http>
  637. ----
  638. ====
  639. to:
  640. ====
  641. .Java
  642. [source,java,role="primary"]
  643. ----
  644. http
  645. .authorizeHttpRequests((authorize) -> authorize
  646. .shouldFilterAllDispatcherTypes(false)
  647. .mvcMatchers("/app/**").hasRole("APP")
  648. // ...
  649. .anyRequest().denyAll()
  650. )
  651. // ...
  652. ----
  653. .Kotlin
  654. [source,kotlin,role="secondary"]
  655. ----
  656. http {
  657. authorizeHttpRequests {
  658. shouldFilterAllDispatcherTypes = false
  659. authorize("/app/**", hasRole("APP"))
  660. // ...
  661. authorize(anyRequest, denyAll)
  662. }
  663. }
  664. ----
  665. .Xml
  666. [source,xml,role="secondary"]
  667. ----
  668. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  669. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  670. <!-- ... -->
  671. <intercept-url pattern="/**" access="denyAll"/>
  672. </http>
  673. ----
  674. ====
  675. ==== Migrate SpEL expressions to `AuthorizationManager`
  676. For authorization rules, Java tends to be easier to test and maintain than SpEL.
  677. As such, `authorizeHttpRequests` does not have a method for declaring a `String` SpEL.
  678. Instead, you can implement your own `AuthorizationManager` implementation or use `WebExpressionAuthorizationManager`.
  679. For completeness, both options will be demonstrated.
  680. First, if you have the following SpEL:
  681. ====
  682. .Java
  683. [source,java,role="primary"]
  684. ----
  685. http
  686. .authorizeRequests((authorize) -> authorize
  687. .filterSecurityInterceptorOncePerRequest(true)
  688. .mvcMatchers("/complicated/**").access("hasRole('ADMIN') || hasAuthority('SCOPE_read')")
  689. // ...
  690. .anyRequest().denyAll()
  691. )
  692. // ...
  693. ----
  694. .Kotlin
  695. [source,kotlin,role="secondary"]
  696. ----
  697. http {
  698. authorizeRequests {
  699. filterSecurityInterceptorOncePerRequest = true
  700. authorize("/complicated/**", access("hasRole('ADMIN') || hasAuthority('SCOPE_read')"))
  701. // ...
  702. authorize(anyRequest, denyAll)
  703. }
  704. }
  705. ----
  706. ====
  707. Then you can compose your own `AuthorizationManager` with Spring Security authorization primitives like so:
  708. ====
  709. .Java
  710. [source,java,role="primary"]
  711. ----
  712. http
  713. .authorizeHttpRequests((authorize) -> authorize
  714. .shouldFilterAllDispatcherTypes(false)
  715. .mvcMatchers("/complicated/**").access(anyOf(hasRole("ADMIN"), hasAuthority("SCOPE_read"))
  716. // ...
  717. .anyRequest().denyAll()
  718. )
  719. // ...
  720. ----
  721. .Kotlin
  722. [source,kotlin,role="secondary"]
  723. ----
  724. http {
  725. authorizeHttpRequests {
  726. shouldFilterAllDispatcherTypes = false
  727. authorize("/complicated/**", access(anyOf(hasRole("ADMIN"), hasAuthority("SCOPE_read"))
  728. // ...
  729. authorize(anyRequest, denyAll)
  730. }
  731. }
  732. ----
  733. ====
  734. Or you can use `WebExpressionAuthorizationManager` in the following way:
  735. ====
  736. .Java
  737. [source,java,role="primary"]
  738. ----
  739. http
  740. .authorizeRequests((authorize) -> authorize
  741. .filterSecurityInterceptorOncePerRequest(true)
  742. .mvcMatchers("/complicated/**").access(
  743. new WebExpressionAuthorizationManager("hasRole('ADMIN') || hasAuthority('SCOPE_read')")
  744. )
  745. // ...
  746. .anyRequest().denyAll()
  747. )
  748. // ...
  749. ----
  750. .Kotlin
  751. [source,kotlin,role="secondary"]
  752. ----
  753. http {
  754. authorizeRequests {
  755. filterSecurityInterceptorOncePerRequest = true
  756. authorize("/complicated/**", access(
  757. WebExpressionAuthorizationManager("hasRole('ADMIN') || hasAuthority('SCOPE_read')"))
  758. )
  759. // ...
  760. authorize(anyRequest, denyAll)
  761. }
  762. }
  763. ----
  764. ====
  765. ==== Switch to filter all dispatcher types
  766. Spring Security 5.8 and earlier only xref:servlet/authorization/architecture.adoc[perform authorization] once per request.
  767. This means that dispatcher types like `FORWARD` and `INCLUDE` that run after `REQUEST` are not secured by default.
  768. It's recommended that Spring Security secure all dispatch types.
  769. As such, in 6.0, Spring Security changes this default.
  770. So, finally, change your authorization rules to filter all dispatcher types.
  771. To do this, change:
  772. ====
  773. .Java
  774. [source,java,role="primary"]
  775. ----
  776. http
  777. .authorizeHttpRequests((authorize) -> authorize
  778. .shouldFilterAllDispatcherTypes(false)
  779. .mvcMatchers("/app/**").hasRole("APP")
  780. // ...
  781. .anyRequest().denyAll()
  782. )
  783. // ...
  784. ----
  785. .Kotlin
  786. [source,kotlin,role="secondary"]
  787. ----
  788. http {
  789. authorizeHttpRequests {
  790. shouldFilterAllDispatcherTypes = false
  791. authorize("/app/**", hasRole("APP"))
  792. // ...
  793. authorize(anyRequest, denyAll)
  794. }
  795. }
  796. ----
  797. .Xml
  798. [source,xml,role="secondary"]
  799. ----
  800. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  801. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  802. <!-- ... -->
  803. <intercept-url pattern="/**" access="denyAll"/>
  804. </http>
  805. ----
  806. ====
  807. to:
  808. ====
  809. .Java
  810. [source,java,role="primary"]
  811. ----
  812. http
  813. .authorizeHttpRequests((authorize) -> authorize
  814. .shouldFilterAllDispatcherTypes(true)
  815. .mvcMatchers("/app/**").hasRole("APP")
  816. // ...
  817. .anyRequest().denyAll()
  818. )
  819. // ...
  820. ----
  821. .Kotlin
  822. [source,kotlin,role="secondary"]
  823. ----
  824. http {
  825. authorizeHttpRequests {
  826. shouldFilterAllDispatcherTypes = true
  827. authorize("/app/**", hasRole("APP"))
  828. // ...
  829. authorize(anyRequest, denyAll)
  830. }
  831. }
  832. ----
  833. .Xml
  834. [source,xml,role="secondary"]
  835. ----
  836. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  837. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  838. <!-- ... -->
  839. <intercept-url pattern="/**" access="denyAll"/>
  840. </http>
  841. ----
  842. ====
  843. [[servlet-authorizationmanager-requests-opt-out]]
  844. ==== Opt-out Steps
  845. In case you had trouble, take a look at these scenarios for optimal opt out behavior:
  846. ===== I cannot secure all dispatcher types
  847. If you cannot secure all dispatcher types, first try and declare which dispatcher types should not require authorization like so:
  848. ====
  849. .Java
  850. [source,java,role="primary"]
  851. ----
  852. http
  853. .authorizeHttpRequests((authorize) -> authorize
  854. .shouldFilterAllDispatcherTypes(true)
  855. .dispatcherTypeMatchers(FORWARD, INCLUDE).permitAll()
  856. .mvcMatchers("/app/**").hasRole("APP")
  857. // ...
  858. .anyRequest().denyAll()
  859. )
  860. // ...
  861. ----
  862. .Kotlin
  863. [source,kotlin,role="secondary"]
  864. ----
  865. http {
  866. authorizeHttpRequests {
  867. shouldFilterAllDispatcherTypes = true
  868. authorize(DispatcherTypeRequestMatcher(FORWARD, INCLUDE), permitAll)
  869. authorize("/app/**", hasRole("APP"))
  870. // ...
  871. authorize(anyRequest, denyAll)
  872. }
  873. }
  874. ----
  875. .Xml
  876. [source,xml,role="secondary"]
  877. ----
  878. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  879. <intercept-url request-matcher-ref="dispatchers"/>
  880. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  881. <!-- ... -->
  882. <intercept-url pattern="/**" access="denyAll"/>
  883. </http>
  884. <bean id="dispatchers" class="org.springframework.security.web.util.matcher.DispatcherTypeRequestMatcher">
  885. <constructor-arg>
  886. <util:list value-type="javax.servlet.DispatcherType">
  887. <value>FORWARD</value>
  888. <value>INCLUDE</value>
  889. </util:list>
  890. </constructor-arg>
  891. </bean>
  892. ----
  893. ====
  894. 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`:
  895. ====
  896. .Java
  897. [source,java,role="primary"]
  898. ----
  899. http
  900. .authorizeHttpRequests((authorize) -> authorize
  901. .filterAllDispatcherTypes(false)
  902. .mvcMatchers("/app/**").hasRole("APP")
  903. // ...
  904. )
  905. // ...
  906. ----
  907. .Kotlin
  908. [source,kotlin,role="secondary"]
  909. ----
  910. http {
  911. authorizeHttpRequests {
  912. filterAllDispatcherTypes = false
  913. authorize("/messages/**", hasRole("APP"))
  914. // ...
  915. }
  916. }
  917. ----
  918. .Xml
  919. [source,xml,role="secondary"]
  920. ----
  921. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  922. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  923. <!-- ... -->
  924. </http>
  925. ----
  926. ====
  927. or, if you are still using `authorizeRequests` or `use-authorization-manager="false"`, set `oncePerRequest` to `true`:
  928. ====
  929. .Java
  930. [source,java,role="primary"]
  931. ----
  932. http
  933. .authorizeRequests((authorize) -> authorize
  934. .filterSecurityInterceptorOncePerRequest(true)
  935. .mvcMatchers("/app/**").hasRole("APP")
  936. // ...
  937. )
  938. // ...
  939. ----
  940. .Kotlin
  941. [source,kotlin,role="secondary"]
  942. ----
  943. http {
  944. authorizeRequests {
  945. filterSecurityInterceptorOncePerRequest = true
  946. authorize("/messages/**", hasRole("APP"))
  947. // ...
  948. }
  949. }
  950. ----
  951. .Xml
  952. [source,xml,role="secondary"]
  953. ----
  954. <http once-per-request="true" use-authorization-manager="false">
  955. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  956. <!-- ... -->
  957. </http>
  958. ----
  959. ====
  960. ===== I cannot declare an authorization rule for all requests
  961. 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:
  962. ====
  963. .Java
  964. [source,java,role="primary"]
  965. ----
  966. http
  967. .authorizeHttpReqeusts((authorize) -> authorize
  968. .mvcMatchers("/app/*").hasRole("APP")
  969. // ...
  970. .anyRequest().permitAll()
  971. )
  972. ----
  973. .Kotlin
  974. [source,kotlin,role="secondary"]
  975. ----
  976. http {
  977. authorizeHttpRequests {
  978. authorize("/app*", hasRole("APP"))
  979. // ...
  980. authorize(anyRequest, permitAll)
  981. }
  982. }
  983. ----
  984. .Xml
  985. [source,xml,role="secondary"]
  986. ----
  987. <http>
  988. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  989. <!-- ... -->
  990. <intercept-url pattern="/**" access="permitAll"/>
  991. </http>
  992. ----
  993. ====
  994. ===== I cannot migrate my SpEL or my `AccessDecisionManager`
  995. 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.
  996. 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.
  997. Second, if you still need your custom `access-decision-manager-ref` or have some other reason to opt out of `AuthorizationManager`, do:
  998. ====
  999. .Xml
  1000. [source,xml,role="secondary"]
  1001. ----
  1002. <http use-authorization-manager="false">
  1003. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1004. <!-- ... -->
  1005. </http>
  1006. ----
  1007. ====
  1008. == Reactive
  1009. === Use `AuthorizationManager` for Method Security
  1010. xref:reactive/authorization/method.adoc[Method Security] has been xref:reactive/authorization/method.adoc#jc-enable-reactive-method-security-authorization-manager[improved] through {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[the `AuthorizationManager` API] and direct use of Spring AOP.
  1011. Should you run into trouble with making these changes, you can follow the
  1012. <<reactive-authorizationmanager-methods-opt-out,opt out steps>> at the end of this section.
  1013. '''
  1014. In Spring Security 5.8, `useAuthorizationManager` was added to {security-api-url}org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurity.html[`@EnableReactiveMethodSecurity`] to allow applications to opt in to ``AuthorizationManager``'s features.
  1015. [[reactive-change-to-useauthorizationmanager]]
  1016. ==== Change `useAuthorizationManager` to `true`
  1017. To opt in, change `useAuthorizationManager` to `true` like so:
  1018. ====
  1019. .Java
  1020. [source,java,role="primary"]
  1021. ----
  1022. @EnableReactiveMethodSecurity
  1023. ----
  1024. .Kotlin
  1025. [source,kotlin,role="secondary"]
  1026. ----
  1027. @EnableReactiveMethodSecurity
  1028. ----
  1029. ====
  1030. changes to:
  1031. ====
  1032. .Java
  1033. [source,java,role="primary"]
  1034. ----
  1035. @EnableReactiveMethodSecurity(useAuthorizationManager = true)
  1036. ----
  1037. .Kotlin
  1038. [source,kotlin,role="secondary"]
  1039. ----
  1040. @EnableReactiveMethodSecurity(useAuthorizationManager = true)
  1041. ----
  1042. ====
  1043. '''
  1044. [[reactive-check-for-annotationconfigurationexceptions]]
  1045. ==== Check for ``AnnotationConfigurationException``s
  1046. `useAuthorizationManager` activates stricter enforcement of Spring Security's non-repeatable or otherwise incompatible annotations.
  1047. If after turning on `useAuthorizationManager` you see ``AnnotationConfigurationException``s in your logs, follow the instructions in the exception message to clean up your application's method security annotation usage.
  1048. [[reactive-authorizationmanager-methods-opt-out]]
  1049. ==== Opt-out Steps
  1050. If you ran into trouble with `AuthorizationManager` for reactive method security, you can opt out by changing:
  1051. ====
  1052. .Java
  1053. [source,java,role="primary"]
  1054. ----
  1055. @EnableReactiveMethodSecurity
  1056. ----
  1057. .Kotlin
  1058. [source,kotlin,role="secondary"]
  1059. ----
  1060. @EnableReactiveMethodSecurity
  1061. ----
  1062. ====
  1063. to:
  1064. ====
  1065. .Java
  1066. [source,java,role="primary"]
  1067. ----
  1068. @EnableReactiveMethodSecurity(useAuthorizationManager = false)
  1069. ----
  1070. .Kotlin
  1071. [source,kotlin,role="secondary"]
  1072. ----
  1073. @EnableReactiveMethodSecurity(useAuthorizationManager = false)
  1074. ----
  1075. ====