migration.adoc 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890
  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. If this breaks your application, then you can explicitly opt into the 5.8 defaults using the following configuration:
  65. .Explicit Configure `CsrfToken` with 5.8 Defaults
  66. ====
  67. .Java
  68. [source,java,role="primary"]
  69. ----
  70. @Bean
  71. DefaultSecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
  72. CsrfTokenRequestAttributeHandler requestHandler = new CsrfTokenRequestAttributeHandler();
  73. // set the name of the attribute the CsrfToken will be populated on
  74. requestHandler.setCsrfRequestAttributeName(null);
  75. http
  76. // ...
  77. .csrf((csrf) -> csrf
  78. .csrfTokenRequestHandler(requestHandler)
  79. );
  80. return http.build();
  81. }
  82. ----
  83. .Kotlin
  84. [source,kotlin,role="secondary"]
  85. ----
  86. @Bean
  87. open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
  88. val requestHandler = CsrfTokenRequestAttributeHandler()
  89. // set the name of the attribute the CsrfToken will be populated on
  90. requestHandler.setCsrfRequestAttributeName(null)
  91. http {
  92. csrf {
  93. csrfTokenRequestHandler = requestHandler
  94. }
  95. }
  96. return http.build()
  97. }
  98. ----
  99. .XML
  100. [source,xml,role="secondary"]
  101. ----
  102. <http>
  103. <!-- ... -->
  104. <csrf request-handler-ref="requestHandler"/>
  105. </http>
  106. <b:bean id="requestHandler"
  107. class="org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler">
  108. <b:property name="csrfRequestAttributeName">
  109. <b:null/>
  110. </b:property>
  111. </b:bean>
  112. ----
  113. ====
  114. === CSRF BREACH Protection
  115. If the steps for <<Defer Loading CsrfToken>> work for you, then you can also opt into Spring Security 6's default support for BREACH protection of the `CsrfToken` using the following configuration:
  116. .`CsrfToken` BREACH Protection
  117. ====
  118. .Java
  119. [source,java,role="primary"]
  120. ----
  121. @Bean
  122. DefaultSecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
  123. XorCsrfTokenRequestAttributeHandler requestHandler = new XorCsrfTokenRequestAttributeHandler();
  124. // set the name of the attribute the CsrfToken will be populated on
  125. requestHandler.setCsrfRequestAttributeName("_csrf");
  126. http
  127. // ...
  128. .csrf((csrf) -> csrf
  129. .csrfTokenRequestHandler(requestHandler)
  130. );
  131. return http.build();
  132. }
  133. ----
  134. .Kotlin
  135. [source,kotlin,role="secondary"]
  136. ----
  137. @Bean
  138. open fun springSecurity(http: HttpSecurity): SecurityFilterChain {
  139. val requestHandler = XorCsrfTokenRequestAttributeHandler()
  140. // set the name of the attribute the CsrfToken will be populated on
  141. requestHandler.setCsrfRequestAttributeName("_csrf")
  142. http {
  143. csrf {
  144. csrfTokenRequestHandler = requestHandler
  145. }
  146. }
  147. return http.build()
  148. }
  149. ----
  150. .XML
  151. [source,xml,role="secondary"]
  152. ----
  153. <http>
  154. <!-- ... -->
  155. <csrf request-handler-ref="requestHandler"/>
  156. </http>
  157. <b:bean id="requestHandler"
  158. class="org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler"
  159. p:csrfRequestAttributeName="_csrf"/>
  160. ----
  161. ====
  162. === Explicit Save SecurityContextRepository
  163. 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`].
  164. Saving must be done just prior to the `HttpServletResponse` being committed and just before `SecurityContextPersistenceFilter`.
  165. 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`).
  166. 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.
  167. 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`.
  168. Users now must explicitly save the `SecurityContext` with the `SecurityContextRepository` if they want the `SecurityContext` to persist between requests.
  169. This removes ambiguity and improves performance by only requiring writing to the `SecurityContextRepository` (i.e. `HttpSession`) when it is necessary.
  170. To opt into the new Spring Security 6 default, the following configuration can be used.
  171. include::partial$servlet/architecture/security-context-explicit.adoc[]
  172. === Deprecation in SecurityContextRepository
  173. In Spring Security 5.7, a new method was added to xref:servlet/authentication/persistence.adoc#securitycontextrepository[`SecurityContextRepository`] with the signature:
  174. Supplier<SecurityContext> loadContext(HttpServletRequest request)
  175. With the addition of xref:servlet/authentication/persistence.adoc#delegatingsecuritycontextrepository[`DelegatingSecurityContextRepository`] in Spring Security 5.8, that method was deprecated in favor of a new method with the signature:
  176. DeferredSecurityContext loadDeferredContext(HttpServletRequest request)
  177. In Spring Security 6, the deprecated method was removed.
  178. If you have implemented `SecurityContextRepository` yourself and added an implementation of the `loadContext(request)` method, you can prepare for Spring Security 6 by removing the implementation of that method and implementing the new method instead.
  179. To get started implementing the new method, use the following example that adapts a `Supplier<SecurityContext>` to provide a `DeferredSecurityContext`:
  180. [NOTE]
  181. ====
  182. The adapted `Supplier` should return `null` when no `SecurityContext` is available, which was not the case with the `Supplier` returned from `loadContext(request)`.
  183. ====
  184. .Adapt `Supplier<SecurityContext>` to `DeferredSecurityContext`
  185. ====
  186. .Java
  187. [source,java,role="primary"]
  188. ----
  189. @Override
  190. public DeferredSecurityContext loadDeferredContext(HttpServletRequest request) {
  191. // Adapt a supplier that returns null when the context is not available
  192. Supplier<SecurityContext> supplier = () -> getContextOrNull(request);
  193. SecurityContextHolderStrategy strategy = SecurityContextHolder.getContextHolderStrategy();
  194. return new DeferredSecurityContext() {
  195. private SecurityContext securityContext;
  196. private boolean isGenerated;
  197. @Override
  198. public SecurityContext get() {
  199. if (this.securityContext == null) {
  200. this.securityContext = supplier.get();
  201. if (this.securityContext == null) {
  202. this.securityContext = strategy.createEmptyContext();
  203. this.isGenerated = true;
  204. }
  205. }
  206. return this.securityContext;
  207. }
  208. @Override
  209. public boolean isGenerated() {
  210. get();
  211. return this.isGenerated;
  212. }
  213. };
  214. }
  215. ----
  216. .Kotlin
  217. [source,kotlin,role="secondary"]
  218. ----
  219. override fun loadDeferredContext(request: HttpServletRequest): DeferredSecurityContext {
  220. // Adapt a supplier that returns null when the context is not available
  221. val supplier: Supplier<SecurityContext?> = SingletonSupplier.of {
  222. getContextOrNull(request)
  223. }
  224. val strategy = SecurityContextHolder.getContextHolderStrategy()
  225. return object : DeferredSecurityContext {
  226. private var securityContext: SecurityContext? = null
  227. private var isGenerated = false
  228. override fun get(): SecurityContext {
  229. if (securityContext == null) {
  230. securityContext = supplier.get()
  231. ?: strategy.createEmptyContext().also { isGenerated = true }
  232. }
  233. return securityContext!!
  234. }
  235. override fun isGenerated(): Boolean {
  236. get()
  237. return isGenerated
  238. }
  239. }
  240. }
  241. ----
  242. ====
  243. [[requestcache-query-optimization]]
  244. === Optimize Querying of `RequestCache`
  245. In Spring Security 5, the default behavior is to query the xref:servlet/architecture.adoc#savedrequests[saved request] on every request.
  246. 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.
  247. In Spring Security 6, the default is that `RequestCache` will only be queried for a cached request if the HTTP parameter `continue` is defined.
  248. This allows Spring Security to avoid unnecessarily reading the `HttpSession` with the `RequestCache`.
  249. In Spring Security 5 the default is to use `HttpSessionRequestCache` which will be queried for a cached request on every request.
  250. 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:
  251. include::partial$servlet/architecture/request-cache-continue.adoc[]
  252. === Use `AuthorizationManager` for Method Security
  253. 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.
  254. 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.
  255. [[servlet-replace-globalmethodsecurity-with-methodsecurity]]
  256. ==== 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]
  257. {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.
  258. 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.
  259. This means that the following two listings are functionally equivalent:
  260. ====
  261. .Java
  262. [source,java,role="primary"]
  263. ----
  264. @EnableGlobalMethodSecurity(prePostEnabled = true)
  265. ----
  266. .Kotlin
  267. [source,kotlin,role="secondary"]
  268. ----
  269. @EnableGlobalMethodSecurity(prePostEnabled = true)
  270. ----
  271. .Xml
  272. [source,xml,role="secondary"]
  273. ----
  274. <global-method-security pre-post-enabled="true"/>
  275. ----
  276. ====
  277. and:
  278. ====
  279. .Java
  280. [source,java,role="primary"]
  281. ----
  282. @EnableMethodSecurity
  283. ----
  284. .Kotlin
  285. [source,kotlin,role="secondary"]
  286. ----
  287. @EnableMethodSecurity
  288. ----
  289. .Xml
  290. [source,xml,role="secondary"]
  291. ----
  292. <method-security/>
  293. ----
  294. ====
  295. For applications not using the pre-post annotations, make sure to turn it off to avoid activating unwanted behavior.
  296. For example, a listing like:
  297. ====
  298. .Java
  299. [source,java,role="primary"]
  300. ----
  301. @EnableGlobalMethodSecurity(securedEnabled = true)
  302. ----
  303. .Kotlin
  304. [source,kotlin,role="secondary"]
  305. ----
  306. @EnableGlobalMethodSecurity(securedEnabled = true)
  307. ----
  308. .Xml
  309. [source,xml,role="secondary"]
  310. ----
  311. <global-method-security secured-enabled="true"/>
  312. ----
  313. ====
  314. should change to:
  315. ====
  316. .Java
  317. [source,java,role="primary"]
  318. ----
  319. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  320. ----
  321. .Kotlin
  322. [source,kotlin,role="secondary"]
  323. ----
  324. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  325. ----
  326. .Xml
  327. [source,xml,role="secondary"]
  328. ----
  329. <method-security secured-enabled="true" pre-post-enabled="false"/>
  330. ----
  331. ====
  332. [[servlet-replace-permissionevaluator-bean-with-methodsecurityexpression-handler]]
  333. ==== Publish a `MethodSecurityExpressionHandler` instead of a `PermissionEvaluator`
  334. `@EnableMethodSecurity` does not pick up a `PermissionEvaluator`.
  335. This helps keep its API simple.
  336. If you have a custom {security-api-url}org/springframework/security/access/PermissionEvaluator.html[`PermissionEvaluator`] `@Bean`, please change it from:
  337. ====
  338. .Java
  339. [source,java,role="primary"]
  340. ----
  341. @Bean
  342. static PermissionEvaluator permissionEvaluator() {
  343. // ... your evaluator
  344. }
  345. ----
  346. .Kotlin
  347. [source,kotlin,role="secondary"]
  348. ----
  349. companion object {
  350. @Bean
  351. fun permissionEvaluator(): PermissionEvaluator {
  352. // ... your evaluator
  353. }
  354. }
  355. ----
  356. ====
  357. to:
  358. ====
  359. .Java
  360. [source,java,role="primary"]
  361. ----
  362. @Bean
  363. static MethodSecurityExpressionHandler expressionHandler() {
  364. var expressionHandler = new DefaultMethodSecurityExpressionHandler();
  365. expressionHandler.setPermissionEvaluator(myPermissionEvaluator);
  366. return expressionHandler;
  367. }
  368. ----
  369. .Kotlin
  370. [source,kotlin,role="secondary"]
  371. ----
  372. companion object {
  373. @Bean
  374. fun expressionHandler(): MethodSecurityExpressionHandler {
  375. val expressionHandler = DefaultMethodSecurityExpressionHandler
  376. expressionHandler.setPermissionEvaluator(myPermissionEvaluator)
  377. return expressionHandler
  378. }
  379. }
  380. ----
  381. ====
  382. ==== Replace any custom method-security ``AccessDecisionManager``s
  383. 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.
  384. The preparation strategy will depend on your reason for each arrangement.
  385. Read on to find the best match for your situation.
  386. ===== I use `UnanimousBased`
  387. 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`].
  388. However, if you do discover that you cannot accept the default authorization managers, you can use `AuthorizationManagers.allOf` to compose your own arrangement.
  389. 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`].
  390. ===== I use `AffirmativeBased`
  391. 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:
  392. ====
  393. .Java
  394. [source,java,role="primary"]
  395. ----
  396. AuthorizationManager<MethodInvocation> authorization = AuthorizationManagers.anyOf(
  397. // ... your list of authorization managers
  398. )
  399. ----
  400. .Kotlin
  401. [source,kotlin,role="secondary"]
  402. ----
  403. val authorization = AuthorizationManagers.anyOf(
  404. // ... your list of authorization managers
  405. )
  406. ----
  407. ====
  408. 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`].
  409. ===== I use `ConsensusBased`
  410. There is no framework-provided equivalent for {security-api-url}org/springframework/security/access/vote/ConsensusBased.html[`ConsensusBased`].
  411. 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.
  412. 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`].
  413. ===== I use a custom `AccessDecisionVoter`
  414. You should either change the class to implement {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] or create an adapter.
  415. Without knowing what your custom voter is doing, it is impossible to recommend a general-purpose solution.
  416. 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:
  417. ====
  418. .Java
  419. [source,java,role="primary"]
  420. ----
  421. public final class PreAuthorizeAuthorizationManagerAdapter implements AuthorizationManager<MethodInvocation> {
  422. private final SecurityMetadataSource metadata;
  423. private final AccessDecisionVoter voter;
  424. public PreAuthorizeAuthorizationManagerAdapter(MethodSecurityExpressionHandler expressionHandler) {
  425. ExpressionBasedAnnotationAttributeFactory attributeFactory =
  426. new ExpressionBasedAnnotationAttributeFactory(expressionHandler);
  427. this.metadata = new PrePostAnnotationSecurityMetadataSource(attributeFactory);
  428. ExpressionBasedPreInvocationAdvice expressionAdvice = new ExpressionBasedPreInvocationAdvice();
  429. expressionAdvice.setExpressionHandler(expressionHandler);
  430. this.voter = new PreInvocationAuthorizationAdviceVoter(expressionAdvice);
  431. }
  432. public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocation invocation) {
  433. List<ConfigAttribute> attributes = this.metadata.getAttributes(invocation, AopUtils.getTargetClass(invocation.getThis()));
  434. int decision = this.voter.vote(authentication.get(), invocation, attributes);
  435. if (decision == ACCESS_GRANTED) {
  436. return new AuthorizationDecision(true);
  437. }
  438. if (decision == ACCESS_DENIED) {
  439. return new AuthorizationDecision(false);
  440. }
  441. return null; // abstain
  442. }
  443. }
  444. ----
  445. ====
  446. 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`].
  447. ===== I use a custom `AfterInvocationManager`
  448. {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] replaces both {security-api-url}org/springframework/security/access/AccessDecisionManager.html[`AccessDecisionManager`] and {security-api-url}org/springframework/security/access/intercept/AfterInvocationManager.html[`AfterInvocationManager`].
  449. The difference is that `AuthorizationManager<MethodInvocation>` replaces `AccessDecisionManager` and `AuthorizationManager<MethodInvocationResult>` replaces `AfterInvocationManager`.
  450. Given that, <<_i_use_a_custom_accessdecisionvoter,the same rules apply for adaptation>>, where the goal this time is to implement `AuthorizationManager<MethodInvocationResult>` instead of `AuthorizationManager<MethodInvocation>` and use `AuthorizationManagerAfterMethodInterceptor` instead of `AuthorizationManagerBeforeMethodInterceptor`.
  451. ===== I use `RunAsManager`
  452. There is currently https://github.com/spring-projects/spring-security/issues/11331[no replacement for `RunAsManager`] though one is being considered.
  453. It is quite straightforward to adapt a `RunAsManager`, though, to the `AuthorizationManager` API, if needed.
  454. Here is some pseudocode to get you started:
  455. ====
  456. .Java
  457. [source,java,role="primary"]
  458. ----
  459. public final class RunAsAuthorizationManagerAdapter<T> implements AuthorizationManager<T> {
  460. private final RunAsManager runAs = new RunAsManagerImpl();
  461. private final SecurityMetadataSource metadata;
  462. private final AuthorizationManager<T> authorization;
  463. // ... constructor
  464. public AuthorizationDecision check(Supplier<Authentication> authentication, T object) {
  465. Supplier<Authentication> wrapped = (auth) -> {
  466. List<ConfigAttribute> attributes = this.metadata.getAttributes(object);
  467. return this.runAs.buildRunAs(auth, object, attributes);
  468. };
  469. return this.authorization.check(wrapped, object);
  470. }
  471. }
  472. ----
  473. ====
  474. 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`].
  475. [[servlet-check-for-annotationconfigurationexceptions]]
  476. ==== Check for ``AnnotationConfigurationException``s
  477. `@EnableMethodSecurity` and `<method-security>` activate stricter enforcement of Spring Security's non-repeatable or otherwise incompatible annotations.
  478. 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.
  479. === Use `AuthorizationManager` for Message Security
  480. 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.
  481. 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.
  482. ==== Ensure all messages have defined authorization rules
  483. The now-deprecated {security-api-url}org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurer.html[message security support] permits all messages by default.
  484. xref:servlet/integrations/websocket.adoc[The new support] has the stronger default of denying all messages.
  485. To prepare for this, ensure that authorization rules exist are declared for every request.
  486. For example, an application configuration like:
  487. ====
  488. .Java
  489. [source,java,role="primary"]
  490. ----
  491. @Override
  492. protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
  493. messages
  494. .simpDestMatchers("/user/queue/errors").permitAll()
  495. .simpDestMatchers("/admin/**").hasRole("ADMIN");
  496. }
  497. ----
  498. .Kotlin
  499. [source,kotlin,role="secondary"]
  500. ----
  501. override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
  502. messages
  503. .simpDestMatchers("/user/queue/errors").permitAll()
  504. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  505. }
  506. ----
  507. .Xml
  508. [source,xml,role="secondary"]
  509. ----
  510. <websocket-message-broker>
  511. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  512. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  513. </websocket-message-broker>
  514. ----
  515. ====
  516. should change to:
  517. ====
  518. .Java
  519. [source,java,role="primary"]
  520. ----
  521. @Override
  522. protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
  523. messages
  524. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  525. .simpDestMatchers("/user/queue/errors").permitAll()
  526. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  527. .anyMessage().denyAll();
  528. }
  529. ----
  530. .Kotlin
  531. [source,kotlin,role="secondary"]
  532. ----
  533. override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
  534. messages
  535. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  536. .simpDestMatchers("/user/queue/errors").permitAll()
  537. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  538. .anyMessage().denyAll()
  539. }
  540. ----
  541. .Xml
  542. [source,xml,role="secondary"]
  543. ----
  544. <websocket-message-broker>
  545. <intercept-message type="CONNECT" access="permitAll"/>
  546. <intercept-message type="DISCONNECT" access="permitAll"/>
  547. <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
  548. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  549. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  550. <intercept-message pattern="/**" access="denyAll"/>
  551. </websocket-message-broker>
  552. ----
  553. ====
  554. ==== Add `@EnableWebSocketSecurity`
  555. [NOTE]
  556. ====
  557. If you want to have CSRF disabled and you are using Java configuration, the migration steps are slightly different.
  558. Instead of using `@EnableWebSocketSecurity`, you will override the appropriate methods in `WebSocketMessageBrokerConfigurer` yourself.
  559. Please see xref:servlet/integrations/websocket.adoc#websocket-sameorigin-disable[the reference manual] for details about this step.
  560. ====
  561. If you are using Java Configuration, add {security-api-url}org/springframework/security/config/annotation/web/socket/EnableWebSocketSecurity.html[`@EnableWebSocketSecurity`] to your application.
  562. For example, you can add it to your websocket security configuration class, like so:
  563. ====
  564. .Java
  565. [source,java,role="primary"]
  566. ----
  567. @EnableWebSocketSecurity
  568. @Configuration
  569. public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
  570. // ...
  571. }
  572. ----
  573. .Kotlin
  574. [source,kotlin,role="secondary"]
  575. ----
  576. @EnableWebSocketSecurity
  577. @Configuration
  578. class WebSocketSecurityConfig: AbstractSecurityWebSocketMessageBrokerConfigurer() {
  579. // ...
  580. }
  581. ----
  582. ====
  583. This will make a prototype instance of `MessageMatcherDelegatingAuthorizationManager.Builder` available to encourage configuration by composition instead of extension.
  584. ==== Use an `AuthorizationManager<Message<?>>` instance
  585. To start using `AuthorizationManager`, you can set the `use-authorization-manager` attribute in XML or you can publish an `AuthorizationManager<Message<?>>` `@Bean` in Java.
  586. For example, the following application configuration:
  587. ====
  588. .Java
  589. [source,java,role="primary"]
  590. ----
  591. @Override
  592. protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
  593. messages
  594. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  595. .simpDestMatchers("/user/queue/errors").permitAll()
  596. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  597. .anyMessage().denyAll();
  598. }
  599. ----
  600. .Kotlin
  601. [source,kotlin,role="secondary"]
  602. ----
  603. override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
  604. messages
  605. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  606. .simpDestMatchers("/user/queue/errors").permitAll()
  607. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  608. .anyMessage().denyAll()
  609. }
  610. ----
  611. .Xml
  612. [source,xml,role="secondary"]
  613. ----
  614. <websocket-message-broker>
  615. <intercept-message type="CONNECT" access="permitAll"/>
  616. <intercept-message type="DISCONNECT" access="permitAll"/>
  617. <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
  618. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  619. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  620. <intercept-message pattern="/**" access="denyAll"/>
  621. </websocket-message-broker>
  622. ----
  623. ====
  624. changes to:
  625. ====
  626. .Java
  627. [source,java,role="primary"]
  628. ----
  629. @Bean
  630. AuthorizationManager<Message<?>> messageSecurity(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
  631. messages
  632. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  633. .simpDestMatchers("/user/queue/errors").permitAll()
  634. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  635. .anyMessage().denyAll();
  636. return messages.build();
  637. }
  638. ----
  639. .Kotlin
  640. [source,kotlin,role="secondary"]
  641. ----
  642. @Bean
  643. fun messageSecurity(val messages: MessageMatcherDelegatingAuthorizationManager.Builder): AuthorizationManager<Message<?>> {
  644. messages
  645. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  646. .simpDestMatchers("/user/queue/errors").permitAll()
  647. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  648. .anyMessage().denyAll()
  649. return messages.build()
  650. }
  651. ----
  652. .Xml
  653. [source,xml,role="secondary"]
  654. ----
  655. <websocket-message-broker use-authorization-manager="true">
  656. <intercept-message type="CONNECT" access="permitAll"/>
  657. <intercept-message type="DISCONNECT" access="permitAll"/>
  658. <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
  659. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  660. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  661. <intercept-message pattern="/**" access="denyAll"/>
  662. </websocket-message-broker>
  663. ----
  664. ====
  665. ==== Stop Implementing `AbstractSecurityWebSocketMessageBrokerConfigurer`
  666. If you are using Java configuration, you can now simply extend `WebSocketMessageBrokerConfigurer`.
  667. For example, if your class that extends `AbstractSecurityWebSocketMessageBrokerConfigurer` is called `WebSocketSecurityConfig`, then:
  668. ====
  669. .Java
  670. [source,java,role="primary"]
  671. ----
  672. @EnableWebSocketSecurity
  673. @Configuration
  674. public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
  675. // ...
  676. }
  677. ----
  678. .Kotlin
  679. [source,kotlin,role="secondary"]
  680. ----
  681. @EnableWebSocketSecurity
  682. @Configuration
  683. class WebSocketSecurityConfig: AbstractSecurityWebSocketMessageBrokerConfigurer() {
  684. // ...
  685. }
  686. ----
  687. ====
  688. changes to:
  689. ====
  690. .Java
  691. [source,java,role="primary"]
  692. ----
  693. @EnableWebSocketSecurity
  694. @Configuration
  695. public class WebSocketSecurityConfig implements WebSocketMessageBrokerConfigurer {
  696. // ...
  697. }
  698. ----
  699. .Kotlin
  700. [source,kotlin,role="secondary"]
  701. ----
  702. @EnableWebSocketSecurity
  703. @Configuration
  704. class WebSocketSecurityConfig: WebSocketMessageBrokerConfigurer {
  705. // ...
  706. }
  707. ----
  708. ====
  709. [[servlet-authorizationmanager-messages-opt-out]]
  710. ==== Opt-out Steps
  711. In case you had trouble, take a look at these scenarios for optimal opt out behavior:
  712. ===== I cannot declare an authorization rule for all requests
  713. 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:
  714. ====
  715. .Java
  716. [source,java,role="primary"]
  717. ----
  718. @Bean
  719. AuthorizationManager<Message<?>> messageSecurity(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
  720. messages
  721. .simpDestMatchers("/user/queue/errors").permitAll()
  722. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  723. // ...
  724. .anyMessage().permitAll();
  725. return messages.build();
  726. }
  727. ----
  728. .Kotlin
  729. [source,kotlin,role="secondary"]
  730. ----
  731. @Bean
  732. fun messageSecurity(val messages: MessageMatcherDelegatingAuthorizationManager.Builder): AuthorizationManager<Message<?>> {
  733. messages
  734. .simpDestMatchers("/user/queue/errors").permitAll()
  735. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  736. // ...
  737. .anyMessage().permitAll();
  738. return messages.build()
  739. }
  740. ----
  741. .Xml
  742. [source,xml,role="secondary"]
  743. ----
  744. <websocket-message-broker use-authorization-manager="true">
  745. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  746. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  747. <!-- ... -->
  748. <intercept-message pattern="/**" access="permitAll"/>
  749. </websocket-message-broker>
  750. ----
  751. ====
  752. ===== I cannot get CSRF working, need some other `AbstractSecurityWebSocketMessageBrokerConfigurer` feature, or am having trouble with `AuthorizationManager`
  753. In the case of Java, you may continue using `AbstractMessageSecurityWebSocketMessageBrokerConfigurer`.
  754. Even though it is deprecated, it will not be removed in 6.0.
  755. In the case of XML, you can opt out of `AuthorizationManager` by setting `use-authorization-manager="false"`:
  756. ====
  757. .Xml
  758. [source,xml,role="secondary"]
  759. ----
  760. <websocket-message-broker>
  761. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  762. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  763. </websocket-message-broker>
  764. ----
  765. ====
  766. to:
  767. ====
  768. .Xml
  769. [source,xml,role="secondary"]
  770. ----
  771. <websocket-message-broker use-authorization-manager="false">
  772. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  773. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  774. </websocket-message-broker>
  775. ----
  776. ====
  777. === Use `AuthorizationManager` for Request Security
  778. 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].
  779. 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.
  780. ==== Ensure that all requests have defined authorization rules
  781. In Spring Security 5.8 and earlier, requests with no authorization rule are permitted by default.
  782. It is a stronger security position to deny by default, thus requiring that authorization rules be clearly defined for every endpoint.
  783. As such, in 6.0, Spring Security by default denies any request that is missing an authorization rule.
  784. 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.
  785. 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.
  786. [NOTE]
  787. ====
  788. You may already have an `anyRequest` rule defined that you are happy with in which case this step can be skipped.
  789. ====
  790. Adding `denyAll` to the end looks like changing:
  791. ====
  792. .Java
  793. [source,java,role="primary"]
  794. ----
  795. http
  796. .authorizeRequests((authorize) -> authorize
  797. .filterSecurityInterceptorOncePerRequest(true)
  798. .mvcMatchers("/app/**").hasRole("APP")
  799. // ...
  800. )
  801. // ...
  802. ----
  803. .Kotlin
  804. [source,kotlin,role="secondary"]
  805. ----
  806. http {
  807. authorizeRequests {
  808. filterSecurityInterceptorOncePerRequest = true
  809. authorize("/app/**", hasRole("APP"))
  810. // ...
  811. }
  812. }
  813. ----
  814. .Xml
  815. [source,xml,role="secondary"]
  816. ----
  817. <http once-per-request="true">
  818. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  819. <!-- ... -->
  820. </http>
  821. ----
  822. ====
  823. to:
  824. ====
  825. .Java
  826. [source,java,role="primary"]
  827. ----
  828. http
  829. .authorizeRequests((authorize) -> authorize
  830. .filterSecurityInterceptorOncePerRequest(true)
  831. .mvcMatchers("/app/**").hasRole("APP")
  832. // ...
  833. .anyRequest().denyAll()
  834. )
  835. // ...
  836. ----
  837. .Kotlin
  838. [source,kotlin,role="secondary"]
  839. ----
  840. http {
  841. authorizeRequests {
  842. filterSecurityInterceptorOncePerRequest = true
  843. authorize("/app/**", hasRole("APP"))
  844. // ...
  845. authorize(anyRequest, denyAll)
  846. }
  847. }
  848. ----
  849. .Xml
  850. [source,xml,role="secondary"]
  851. ----
  852. <http once-per-request="true">
  853. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  854. <!-- ... -->
  855. <intercept-url pattern="/**" access="denyAll"/>
  856. </http>
  857. ----
  858. ====
  859. If you have already migrated to `authorizeHttpRequests`, the recommended change is the same.
  860. ==== Switch to `AuthorizationManager`
  861. 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.
  862. Change:
  863. ====
  864. .Java
  865. [source,java,role="primary"]
  866. ----
  867. http
  868. .authorizeRequests((authorize) -> authorize
  869. .filterSecurityInterceptorOncePerRequest(true)
  870. .mvcMatchers("/app/**").hasRole("APP")
  871. // ...
  872. .anyRequest().denyAll()
  873. )
  874. // ...
  875. ----
  876. .Kotlin
  877. [source,kotlin,role="secondary"]
  878. ----
  879. http {
  880. authorizeRequests {
  881. filterSecurityInterceptorOncePerRequest = true
  882. authorize("/app/**", hasRole("APP"))
  883. // ...
  884. authorize(anyRequest, denyAll)
  885. }
  886. }
  887. ----
  888. .Xml
  889. [source,xml,role="secondary"]
  890. ----
  891. <http once-per-request="true">
  892. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  893. <!-- ... -->
  894. <intercept-url pattern="/**" access="denyAll"/>
  895. </http>
  896. ----
  897. ====
  898. to:
  899. ====
  900. .Java
  901. [source,java,role="primary"]
  902. ----
  903. http
  904. .authorizeHttpRequests((authorize) -> authorize
  905. .shouldFilterAllDispatcherTypes(false)
  906. .mvcMatchers("/app/**").hasRole("APP")
  907. // ...
  908. .anyRequest().denyAll()
  909. )
  910. // ...
  911. ----
  912. .Kotlin
  913. [source,kotlin,role="secondary"]
  914. ----
  915. http {
  916. authorizeHttpRequests {
  917. shouldFilterAllDispatcherTypes = false
  918. authorize("/app/**", hasRole("APP"))
  919. // ...
  920. authorize(anyRequest, denyAll)
  921. }
  922. }
  923. ----
  924. .Xml
  925. [source,xml,role="secondary"]
  926. ----
  927. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  928. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  929. <!-- ... -->
  930. <intercept-url pattern="/**" access="denyAll"/>
  931. </http>
  932. ----
  933. ====
  934. ==== Migrate SpEL expressions to `AuthorizationManager`
  935. For authorization rules, Java tends to be easier to test and maintain than SpEL.
  936. As such, `authorizeHttpRequests` does not have a method for declaring a `String` SpEL.
  937. Instead, you can implement your own `AuthorizationManager` implementation or use `WebExpressionAuthorizationManager`.
  938. For completeness, both options will be demonstrated.
  939. First, if you have the following SpEL:
  940. ====
  941. .Java
  942. [source,java,role="primary"]
  943. ----
  944. http
  945. .authorizeRequests((authorize) -> authorize
  946. .filterSecurityInterceptorOncePerRequest(true)
  947. .mvcMatchers("/complicated/**").access("hasRole('ADMIN') || hasAuthority('SCOPE_read')")
  948. // ...
  949. .anyRequest().denyAll()
  950. )
  951. // ...
  952. ----
  953. .Kotlin
  954. [source,kotlin,role="secondary"]
  955. ----
  956. http {
  957. authorizeRequests {
  958. filterSecurityInterceptorOncePerRequest = true
  959. authorize("/complicated/**", access("hasRole('ADMIN') || hasAuthority('SCOPE_read')"))
  960. // ...
  961. authorize(anyRequest, denyAll)
  962. }
  963. }
  964. ----
  965. ====
  966. Then you can compose your own `AuthorizationManager` with Spring Security authorization primitives like so:
  967. ====
  968. .Java
  969. [source,java,role="primary"]
  970. ----
  971. http
  972. .authorizeHttpRequests((authorize) -> authorize
  973. .shouldFilterAllDispatcherTypes(false)
  974. .mvcMatchers("/complicated/**").access(anyOf(hasRole("ADMIN"), hasAuthority("SCOPE_read"))
  975. // ...
  976. .anyRequest().denyAll()
  977. )
  978. // ...
  979. ----
  980. .Kotlin
  981. [source,kotlin,role="secondary"]
  982. ----
  983. http {
  984. authorizeHttpRequests {
  985. shouldFilterAllDispatcherTypes = false
  986. authorize("/complicated/**", access(anyOf(hasRole("ADMIN"), hasAuthority("SCOPE_read"))
  987. // ...
  988. authorize(anyRequest, denyAll)
  989. }
  990. }
  991. ----
  992. ====
  993. Or you can use `WebExpressionAuthorizationManager` in the following way:
  994. ====
  995. .Java
  996. [source,java,role="primary"]
  997. ----
  998. http
  999. .authorizeRequests((authorize) -> authorize
  1000. .filterSecurityInterceptorOncePerRequest(true)
  1001. .mvcMatchers("/complicated/**").access(
  1002. new WebExpressionAuthorizationManager("hasRole('ADMIN') || hasAuthority('SCOPE_read')")
  1003. )
  1004. // ...
  1005. .anyRequest().denyAll()
  1006. )
  1007. // ...
  1008. ----
  1009. .Kotlin
  1010. [source,kotlin,role="secondary"]
  1011. ----
  1012. http {
  1013. authorizeRequests {
  1014. filterSecurityInterceptorOncePerRequest = true
  1015. authorize("/complicated/**", access(
  1016. WebExpressionAuthorizationManager("hasRole('ADMIN') || hasAuthority('SCOPE_read')"))
  1017. )
  1018. // ...
  1019. authorize(anyRequest, denyAll)
  1020. }
  1021. }
  1022. ----
  1023. ====
  1024. ==== Switch to filter all dispatcher types
  1025. Spring Security 5.8 and earlier only xref:servlet/authorization/architecture.adoc[perform authorization] once per request.
  1026. This means that dispatcher types like `FORWARD` and `INCLUDE` that run after `REQUEST` are not secured by default.
  1027. It's recommended that Spring Security secure all dispatch types.
  1028. As such, in 6.0, Spring Security changes this default.
  1029. So, finally, change your authorization rules to filter all dispatcher types.
  1030. To do this, change:
  1031. ====
  1032. .Java
  1033. [source,java,role="primary"]
  1034. ----
  1035. http
  1036. .authorizeHttpRequests((authorize) -> authorize
  1037. .shouldFilterAllDispatcherTypes(false)
  1038. .mvcMatchers("/app/**").hasRole("APP")
  1039. // ...
  1040. .anyRequest().denyAll()
  1041. )
  1042. // ...
  1043. ----
  1044. .Kotlin
  1045. [source,kotlin,role="secondary"]
  1046. ----
  1047. http {
  1048. authorizeHttpRequests {
  1049. shouldFilterAllDispatcherTypes = false
  1050. authorize("/app/**", hasRole("APP"))
  1051. // ...
  1052. authorize(anyRequest, denyAll)
  1053. }
  1054. }
  1055. ----
  1056. .Xml
  1057. [source,xml,role="secondary"]
  1058. ----
  1059. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  1060. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1061. <!-- ... -->
  1062. <intercept-url pattern="/**" access="denyAll"/>
  1063. </http>
  1064. ----
  1065. ====
  1066. to:
  1067. ====
  1068. .Java
  1069. [source,java,role="primary"]
  1070. ----
  1071. http
  1072. .authorizeHttpRequests((authorize) -> authorize
  1073. .shouldFilterAllDispatcherTypes(true)
  1074. .mvcMatchers("/app/**").hasRole("APP")
  1075. // ...
  1076. .anyRequest().denyAll()
  1077. )
  1078. // ...
  1079. ----
  1080. .Kotlin
  1081. [source,kotlin,role="secondary"]
  1082. ----
  1083. http {
  1084. authorizeHttpRequests {
  1085. shouldFilterAllDispatcherTypes = true
  1086. authorize("/app/**", hasRole("APP"))
  1087. // ...
  1088. authorize(anyRequest, denyAll)
  1089. }
  1090. }
  1091. ----
  1092. .Xml
  1093. [source,xml,role="secondary"]
  1094. ----
  1095. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  1096. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1097. <!-- ... -->
  1098. <intercept-url pattern="/**" access="denyAll"/>
  1099. </http>
  1100. ----
  1101. ====
  1102. ==== Replace any custom filter-security ``AccessDecisionManager``s
  1103. 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.
  1104. The preparation strategy will depend on your reason for each arrangement.
  1105. Read on to find the best match for your situation.
  1106. ===== I use `UnanimousBased`
  1107. 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:
  1108. ====
  1109. .Java
  1110. [source,java,role="primary"]
  1111. ----
  1112. @Bean
  1113. AuthorizationManager<RequestAuthorizationContext> requestAuthorization() {
  1114. PolicyAuthorizationManager policy = ...;
  1115. LocalAuthorizationManager local = ...;
  1116. return AuthorizationMangers.allOf(policy, local);
  1117. }
  1118. ----
  1119. .Kotlin
  1120. [source,kotlin,role="secondary"]
  1121. ----
  1122. @Bean
  1123. fun requestAuthorization(): AuthorizationManager<RequestAuthorizationContext> {
  1124. val policy: PolicyAuthorizationManager = ...
  1125. val local: LocalAuthorizationManager = ...
  1126. return AuthorizationMangers.allOf(policy, local)
  1127. }
  1128. ----
  1129. .Xml
  1130. [source,xml,role="secondary"]
  1131. ----
  1132. <bean id="requestAuthorization" class="org.springframework.security.authorization.AuthorizationManagers"
  1133. factory-method="allOf">
  1134. <constructor-arg>
  1135. <util:list>
  1136. <bean class="my.PolicyAuthorizationManager"/>
  1137. <bean class="my.LocalAuthorizationManager"/>
  1138. </util:list>
  1139. </constructor-arg>
  1140. </bean>
  1141. ----
  1142. ====
  1143. then, wire it into the DSL like so:
  1144. ====
  1145. .Java
  1146. [source,java,role="primary"]
  1147. ----
  1148. http
  1149. .authorizeHttpRequests((authorize) -> authorize.anyRequest().access(requestAuthorization))
  1150. // ...
  1151. ----
  1152. .Kotlin
  1153. [source,kotlin,role="secondary"]
  1154. ----
  1155. http {
  1156. authorizeHttpRequests {
  1157. authorize(anyRequest, requestAuthorization)
  1158. }
  1159. // ...
  1160. }
  1161. ----
  1162. .Xml
  1163. [source,xml,role="secondary"]
  1164. ----
  1165. <http authorization-manager-ref="requestAuthorization"/>
  1166. ----
  1167. ====
  1168. [NOTE]
  1169. ====
  1170. `authorizeHttpRequests` is designed so that you can apply a custom `AuthorizationManager` to any url pattern.
  1171. See xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[the reference] for more details.
  1172. ====
  1173. ===== I use `AffirmativeBased`
  1174. 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:
  1175. ====
  1176. .Java
  1177. [source,java,role="primary"]
  1178. ----
  1179. @Bean
  1180. AuthorizationManager<RequestAuthorizationContext> requestAuthorization() {
  1181. PolicyAuthorizationManager policy = ...;
  1182. LocalAuthorizationManager local = ...;
  1183. return AuthorizationMangers.anyOf(policy, local);
  1184. }
  1185. ----
  1186. .Kotlin
  1187. [source,kotlin,role="secondary"]
  1188. ----
  1189. @Bean
  1190. fun requestAuthorization(): AuthorizationManager<RequestAuthorizationContext> {
  1191. val policy: PolicyAuthorizationManager = ...
  1192. val local: LocalAuthorizationManager = ...
  1193. return AuthorizationMangers.anyOf(policy, local)
  1194. }
  1195. ----
  1196. .Xml
  1197. [source,xml,role="secondary"]
  1198. ----
  1199. <bean id="requestAuthorization" class="org.springframework.security.authorization.AuthorizationManagers"
  1200. factory-method="anyOf">
  1201. <constructor-arg>
  1202. <util:list>
  1203. <bean class="my.PolicyAuthorizationManager"/>
  1204. <bean class="my.LocalAuthorizationManager"/>
  1205. </util:list>
  1206. </constructor-arg>
  1207. </bean>
  1208. ----
  1209. ====
  1210. then, wire it into the DSL like so:
  1211. ====
  1212. .Java
  1213. [source,java,role="primary"]
  1214. ----
  1215. http
  1216. .authorizeHttpRequests((authorize) -> authorize.anyRequest().access(requestAuthorization))
  1217. // ...
  1218. ----
  1219. .Kotlin
  1220. [source,kotlin,role="secondary"]
  1221. ----
  1222. http {
  1223. authorizeHttpRequests {
  1224. authorize(anyRequest, requestAuthorization)
  1225. }
  1226. // ...
  1227. }
  1228. ----
  1229. .Xml
  1230. [source,xml,role="secondary"]
  1231. ----
  1232. <http authorization-manager-ref="requestAuthorization"/>
  1233. ----
  1234. ====
  1235. [NOTE]
  1236. ====
  1237. `authorizeHttpRequests` is designed so that you can apply a custom `AuthorizationManager` to any url pattern.
  1238. See xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[the reference] for more details.
  1239. ====
  1240. ===== I use `ConsensusBased`
  1241. There is no framework-provided equivalent for {security-api-url}org/springframework/security/access/vote/ConsensusBased.html[`ConsensusBased`].
  1242. 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.
  1243. 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`].
  1244. ===== I use a custom `AccessDecisionVoter`
  1245. You should either change the class to implement {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] or create an adapter.
  1246. Without knowing what your custom voter is doing, it is impossible to recommend a general-purpose solution.
  1247. 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:
  1248. ====
  1249. .Java
  1250. [source,java,role="primary"]
  1251. ----
  1252. public final class AnyRequestAuthenticatedAuthorizationManagerAdapter implements AuthorizationManager<RequestAuthorizationContext> {
  1253. private final SecurityMetadataSource metadata;
  1254. private final AccessDecisionVoter voter;
  1255. public PreAuthorizeAuthorizationManagerAdapter(SecurityExpressionHandler expressionHandler) {
  1256. Map<RequestMatcher, List<ConfigAttribute>> requestMap = Collections.singletonMap(
  1257. AnyRequestMatcher.INSTANCE, Collections.singletonList(new SecurityConfig("authenticated")));
  1258. this.metadata = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
  1259. WebExpressionVoter voter = new WebExpressionVoter();
  1260. voter.setExpressionHandler(expressionHandler);
  1261. this.voter = voter;
  1262. }
  1263. public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
  1264. List<ConfigAttribute> attributes = this.metadata.getAttributes(context);
  1265. int decision = this.voter.vote(authentication.get(), invocation, attributes);
  1266. if (decision == ACCESS_GRANTED) {
  1267. return new AuthorizationDecision(true);
  1268. }
  1269. if (decision == ACCESS_DENIED) {
  1270. return new AuthorizationDecision(false);
  1271. }
  1272. return null; // abstain
  1273. }
  1274. }
  1275. ----
  1276. ====
  1277. 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`].
  1278. [[servlet-authorizationmanager-requests-opt-out]]
  1279. ==== Opt-out Steps
  1280. In case you had trouble, take a look at these scenarios for optimal opt out behavior:
  1281. ===== I cannot secure all dispatcher types
  1282. If you cannot secure all dispatcher types, first try and declare which dispatcher types should not require authorization like so:
  1283. ====
  1284. .Java
  1285. [source,java,role="primary"]
  1286. ----
  1287. http
  1288. .authorizeHttpRequests((authorize) -> authorize
  1289. .shouldFilterAllDispatcherTypes(true)
  1290. .dispatcherTypeMatchers(FORWARD, INCLUDE).permitAll()
  1291. .mvcMatchers("/app/**").hasRole("APP")
  1292. // ...
  1293. .anyRequest().denyAll()
  1294. )
  1295. // ...
  1296. ----
  1297. .Kotlin
  1298. [source,kotlin,role="secondary"]
  1299. ----
  1300. http {
  1301. authorizeHttpRequests {
  1302. shouldFilterAllDispatcherTypes = true
  1303. authorize(DispatcherTypeRequestMatcher(FORWARD, INCLUDE), permitAll)
  1304. authorize("/app/**", hasRole("APP"))
  1305. // ...
  1306. authorize(anyRequest, denyAll)
  1307. }
  1308. }
  1309. ----
  1310. .Xml
  1311. [source,xml,role="secondary"]
  1312. ----
  1313. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  1314. <intercept-url request-matcher-ref="dispatchers"/>
  1315. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1316. <!-- ... -->
  1317. <intercept-url pattern="/**" access="denyAll"/>
  1318. </http>
  1319. <bean id="dispatchers" class="org.springframework.security.web.util.matcher.DispatcherTypeRequestMatcher">
  1320. <constructor-arg>
  1321. <util:list value-type="javax.servlet.DispatcherType">
  1322. <value>FORWARD</value>
  1323. <value>INCLUDE</value>
  1324. </util:list>
  1325. </constructor-arg>
  1326. </bean>
  1327. ----
  1328. ====
  1329. 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`:
  1330. ====
  1331. .Java
  1332. [source,java,role="primary"]
  1333. ----
  1334. http
  1335. .authorizeHttpRequests((authorize) -> authorize
  1336. .filterAllDispatcherTypes(false)
  1337. .mvcMatchers("/app/**").hasRole("APP")
  1338. // ...
  1339. )
  1340. // ...
  1341. ----
  1342. .Kotlin
  1343. [source,kotlin,role="secondary"]
  1344. ----
  1345. http {
  1346. authorizeHttpRequests {
  1347. filterAllDispatcherTypes = false
  1348. authorize("/messages/**", hasRole("APP"))
  1349. // ...
  1350. }
  1351. }
  1352. ----
  1353. .Xml
  1354. [source,xml,role="secondary"]
  1355. ----
  1356. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  1357. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1358. <!-- ... -->
  1359. </http>
  1360. ----
  1361. ====
  1362. or, if you are still using `authorizeRequests` or `use-authorization-manager="false"`, set `oncePerRequest` to `true`:
  1363. ====
  1364. .Java
  1365. [source,java,role="primary"]
  1366. ----
  1367. http
  1368. .authorizeRequests((authorize) -> authorize
  1369. .filterSecurityInterceptorOncePerRequest(true)
  1370. .mvcMatchers("/app/**").hasRole("APP")
  1371. // ...
  1372. )
  1373. // ...
  1374. ----
  1375. .Kotlin
  1376. [source,kotlin,role="secondary"]
  1377. ----
  1378. http {
  1379. authorizeRequests {
  1380. filterSecurityInterceptorOncePerRequest = true
  1381. authorize("/messages/**", hasRole("APP"))
  1382. // ...
  1383. }
  1384. }
  1385. ----
  1386. .Xml
  1387. [source,xml,role="secondary"]
  1388. ----
  1389. <http once-per-request="true" use-authorization-manager="false">
  1390. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1391. <!-- ... -->
  1392. </http>
  1393. ----
  1394. ====
  1395. ===== I cannot declare an authorization rule for all requests
  1396. 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:
  1397. ====
  1398. .Java
  1399. [source,java,role="primary"]
  1400. ----
  1401. http
  1402. .authorizeHttpReqeusts((authorize) -> authorize
  1403. .mvcMatchers("/app/*").hasRole("APP")
  1404. // ...
  1405. .anyRequest().permitAll()
  1406. )
  1407. ----
  1408. .Kotlin
  1409. [source,kotlin,role="secondary"]
  1410. ----
  1411. http {
  1412. authorizeHttpRequests {
  1413. authorize("/app*", hasRole("APP"))
  1414. // ...
  1415. authorize(anyRequest, permitAll)
  1416. }
  1417. }
  1418. ----
  1419. .Xml
  1420. [source,xml,role="secondary"]
  1421. ----
  1422. <http>
  1423. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1424. <!-- ... -->
  1425. <intercept-url pattern="/**" access="permitAll"/>
  1426. </http>
  1427. ----
  1428. ====
  1429. ===== I cannot migrate my SpEL or my `AccessDecisionManager`
  1430. 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.
  1431. 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.
  1432. Second, if you still need your custom `access-decision-manager-ref` or have some other reason to opt out of `AuthorizationManager`, do:
  1433. ====
  1434. .Xml
  1435. [source,xml,role="secondary"]
  1436. ----
  1437. <http use-authorization-manager="false">
  1438. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1439. <!-- ... -->
  1440. </http>
  1441. ----
  1442. ====
  1443. === Propagate ``AuthenticationServiceException``s
  1444. {security-api-url}org/springframework/security/web/authentication/AuthenticationFilter.html[`AuthenticationFilter`] propagates {security-api-url}org/springframework/security/authentication/AuthenticationServiceException.html[``AuthenticationServiceException``]s to the {security-api-url}org/springframework/security/authentication/AuthenticationEntryPoint.html[`AuthenticationEntryPoint`].
  1445. Because ``AuthenticationServiceException``s represent a server-side error instead of a client-side error, in 6.0, this changes to propagate them to the container.
  1446. ==== Configure `AuthenticationFailureHandler` to rethrow ``AuthenticationServiceException``s
  1447. To prepare for the 6.0 default, wire `AuthenticationFilter` instances with a `AuthenticationFailureHandler` that rethrows ``AuthenticationServiceException``s, like so:
  1448. ====
  1449. .Java
  1450. [source,java,role="primary"]
  1451. ----
  1452. AuthenticationFilter authenticationFilter = new AuthenticationFilter(...);
  1453. AuthenticationEntryPointFailureHandler handler = new AuthenticationEntryPointFailureHandler(...);
  1454. handler.setRethrowAuthenticationServiceException(true);
  1455. authenticationFilter.setAuthenticationFailureHandler(handler);
  1456. ----
  1457. .Kotlin
  1458. [source,kotlin,role="secondary"]
  1459. ----
  1460. val authenticationFilter: AuthenticationFilter = new AuthenticationFilter(...)
  1461. val handler: AuthenticationEntryPointFailureHandler = new AuthenticationEntryPointFailureHandler(...)
  1462. handler.setRethrowAuthenticationServiceException(true)
  1463. authenticationFilter.setAuthenticationFailureHandler(handler)
  1464. ----
  1465. .Xml
  1466. [source,xml,role="secondary"]
  1467. ----
  1468. <bean id="authenticationFilter" class="org.springframework.security.web.authentication.AuthenticationFilter">
  1469. <!-- ... -->
  1470. <property ref="authenticationFailureHandler"/>
  1471. </bean>
  1472. <bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.AuthenticationEntryPointFailureHandler">
  1473. <property name="rethrowAuthenticationServiceException" value="true"/>
  1474. </bean>
  1475. ----
  1476. ====
  1477. [[servlet-authenticationfailurehandler-opt-out]]
  1478. ==== Opt-out Steps
  1479. If rethrowing ``AuthenticationServiceException``s gives you trouble, you can set the value to false instead of taking the 6.0 default, like so:
  1480. ====
  1481. .Java
  1482. [source,java,role="primary"]
  1483. ----
  1484. AuthenticationFilter authenticationFilter = new AuthenticationFilter(...);
  1485. AuthenticationEntryPointFailureHandler handler = new AuthenticationEntryPointFailureHandler(...);
  1486. handler.setRethrowAuthenticationServiceException(false);
  1487. authenticationFilter.setAuthenticationFailureHandler(handler);
  1488. ----
  1489. .Kotlin
  1490. [source,kotlin,role="secondary"]
  1491. ----
  1492. val authenticationFilter: AuthenticationFilter = new AuthenticationFilter(...)
  1493. val handler: AuthenticationEntryPointFailureHandler = new AuthenticationEntryPointFailureHandler(...)
  1494. handler.setRethrowAuthenticationServiceException(false)
  1495. authenticationFilter.setAuthenticationFailureHandler(handler)
  1496. ----
  1497. .Xml
  1498. [source,xml,role="secondary"]
  1499. ----
  1500. <bean id="authenticationFilter" class="org.springframework.security.web.authentication.AuthenticationFilter">
  1501. <!-- ... -->
  1502. <property ref="authenticationFailureHandler"/>
  1503. </bean>
  1504. <bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.AuthenticationEntryPointFailureHandler">
  1505. <property name="rethrowAuthenticationServiceException" value="false"/>
  1506. </bean>
  1507. ----
  1508. ====
  1509. [[servlet-opt-in-sha256-rememberme]]
  1510. === Use SHA-256 in Remember Me
  1511. The `TokenBasedRememberMeServices` implementation now supports SHA-256 for the Remember Me token and this is the default in Spring Security 6.
  1512. This change makes the implementation more secure by default since MD5 is already proven to be a weak hashing algorithm and vulnerable against collision attacks and modular differential attacks.
  1513. The new generated tokens now have the information of which algorithm was used to generate the token and that information is used in order to match it.
  1514. If the algorithm name is not present, then the `matchingAlgorithm` property is used to check the token.
  1515. This allows for a smooth transition from MD5 to SHA-256.
  1516. To opt into the new Spring Security 6 default to encode the tokens while still being able to decode tokens encoded with MD5, you can set the `encodingAlgorithm` property to SHA-256 and the `matchingAlgorithm` property to MD5.
  1517. See the xref:servlet/authentication/rememberme.adoc#_tokenbasedremembermeservices[reference documentation] and the {security-api-url}org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.html[API docs] for more information.
  1518. [[servlet-opt-in-sha256-sha256-encoding]]
  1519. .Use Spring Security 6 defaults for encoding, SHA-256 for encoding and MD5 for matching
  1520. ====
  1521. .Java
  1522. [source,java,role="primary"]
  1523. ----
  1524. @Configuration
  1525. @EnableWebSecurity
  1526. public class SecurityConfig {
  1527. @Bean
  1528. SecurityFilterChain securityFilterChain(HttpSecurity http, RememberMeServices rememberMeServices) throws Exception {
  1529. http
  1530. // ...
  1531. .rememberMe((remember) -> remember
  1532. .rememberMeServices(rememberMeServices)
  1533. );
  1534. return http.build();
  1535. }
  1536. @Bean
  1537. RememberMeServices rememberMeServices(UserDetailsService userDetailsService) {
  1538. RememberMeTokenAlgorithm encodingAlgorithm = RememberMeTokenAlgorithm.SHA256;
  1539. TokenBasedRememberMeServices rememberMe = new TokenBasedRememberMeServices(myKey, userDetailsService, encodingAlgorithm);
  1540. rememberMe.setMatchingAlgorithm(RememberMeTokenAlgorithm.MD5);
  1541. return rememberMe;
  1542. }
  1543. }
  1544. ----
  1545. .XML
  1546. [source,xml,role="secondary"]
  1547. ----
  1548. <http>
  1549. <remember-me services-ref="rememberMeServices"/>
  1550. </http>
  1551. <bean id="rememberMeServices" class=
  1552. "org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
  1553. <property name="userDetailsService" ref="myUserDetailsService"/>
  1554. <property name="key" value="springRocks"/>
  1555. <property name="matchingAlgorithm" value="MD5"/>
  1556. <property name="encodingAlgorithm" value="SHA256"/>
  1557. </bean>
  1558. ----
  1559. ====
  1560. At some point, you will want to fully migrate to Spring Security 6 defaults. But how do you know when it is safe to do so?
  1561. Let's suppose that you deployed your application using SHA-256 as the encoding algorithm (as you have done <<servlet-opt-in-sha256-sha256-encoding,here>>) on November 1st, if you have the value for the `tokenValiditySeconds` property set to N days (14 is the default), you can migrate to SHA-256 N days after November 1st (which is November 15th in this example).
  1562. By that time, all the tokens generated with MD5 will have expired.
  1563. .Use Spring Security 6 defaults, SHA-256 for both encoding and matching
  1564. ====
  1565. .Java
  1566. [source,java,role="primary"]
  1567. ----
  1568. @Configuration
  1569. @EnableWebSecurity
  1570. public class SecurityConfig {
  1571. @Bean
  1572. SecurityFilterChain securityFilterChain(HttpSecurity http, RememberMeServices rememberMeServices) throws Exception {
  1573. http
  1574. // ...
  1575. .rememberMe((remember) -> remember
  1576. .rememberMeServices(rememberMeServices)
  1577. );
  1578. return http.build();
  1579. }
  1580. @Bean
  1581. RememberMeServices rememberMeServices(UserDetailsService userDetailsService) {
  1582. RememberMeTokenAlgorithm encodingAlgorithm = RememberMeTokenAlgorithm.SHA256;
  1583. TokenBasedRememberMeServices rememberMe = new TokenBasedRememberMeServices(myKey, userDetailsService, encodingAlgorithm);
  1584. rememberMe.setMatchingAlgorithm(RememberMeTokenAlgorithm.SHA256);
  1585. return rememberMe;
  1586. }
  1587. }
  1588. ----
  1589. .XML
  1590. [source,xml,role="secondary"]
  1591. ----
  1592. <http>
  1593. <remember-me services-ref="rememberMeServices"/>
  1594. </http>
  1595. <bean id="rememberMeServices" class=
  1596. "org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
  1597. <property name="userDetailsService" ref="myUserDetailsService"/>
  1598. <property name="key" value="springRocks"/>
  1599. <property name="matchingAlgorithm" value="SHA256"/>
  1600. <property name="encodingAlgorithm" value="SHA256"/>
  1601. </bean>
  1602. ----
  1603. ====
  1604. If you are having problems with the Spring Security 6 defaults, you can explicitly opt into 5.8 defaults using the following configuration:
  1605. .Use MD5 for both encoding and matching algorithms
  1606. ====
  1607. .Java
  1608. [source,java,role="primary"]
  1609. ----
  1610. @Configuration
  1611. @EnableWebSecurity
  1612. public class SecurityConfig {
  1613. @Bean
  1614. SecurityFilterChain securityFilterChain(HttpSecurity http, RememberMeServices rememberMeServices) throws Exception {
  1615. http
  1616. // ...
  1617. .rememberMe((remember) -> remember
  1618. .rememberMeServices(rememberMeServices)
  1619. );
  1620. return http.build();
  1621. }
  1622. @Bean
  1623. RememberMeServices rememberMeServices(UserDetailsService userDetailsService) {
  1624. RememberMeTokenAlgorithm encodingAlgorithm = RememberMeTokenAlgorithm.MD5;
  1625. TokenBasedRememberMeServices rememberMe = new TokenBasedRememberMeServices(myKey, userDetailsService, encodingAlgorithm);
  1626. rememberMe.setMatchingAlgorithm(RememberMeTokenAlgorithm.MD5);
  1627. return rememberMe;
  1628. }
  1629. }
  1630. ----
  1631. .XML
  1632. [source,xml,role="secondary"]
  1633. ----
  1634. <http>
  1635. <remember-me services-ref="rememberMeServices"/>
  1636. </http>
  1637. <bean id="rememberMeServices" class=
  1638. "org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
  1639. <property name="userDetailsService" ref="myUserDetailsService"/>
  1640. <property name="key" value="springRocks"/>
  1641. <property name="matchingAlgorithm" value="MD5"/>
  1642. <property name="encodingAlgorithm" value="MD5"/>
  1643. </bean>
  1644. ----
  1645. ====
  1646. === Stop Using SAML 2.0 `Converter` constructors
  1647. In an early release of Spring Security's SAML 2.0 support, `Saml2MetadataFilter` and `Saml2AuthenticationTokenConverter` shipped with constructors of type `Converter`.
  1648. This level of abstraction made it tricky to evolve the class and so a dedicated interface `RelyingPartyRegistrationResolver` was introduced in a later release.
  1649. In 6.0, the `Converter` constructors are removed.
  1650. To prepare for this in 5.8, change classes that implement `Converter<HttpServletRequest, RelyingPartyRegistration>` to instead implement `RelyingPartyRegistrationResolver`.
  1651. === Change to Using `Saml2AuthenticationRequestResolver`
  1652. `Saml2AuthenticationContextResolver` and `Saml2AuthenticationRequestFactory` are removed in 6.0 as is the `Saml2WebSsoAuthenticationRequestFilter` that requires them.
  1653. They are replaced by `Saml2AuthenticationRequestResolver` and a new constructor in `Saml2WebSsoAuthenticationRequestFilter`.
  1654. The new interface removes an unnecessary transport object between the two classes.
  1655. Most applications need do nothing; however, if you use or configure `Saml2AuthenticationRequestContextResolver` or `Saml2AuthenticationRequestFactory`, try the following steps to convert instead use `Saml2AuthenticationRequestResolver`.
  1656. ==== Use `setAuthnRequestCustomizer` instead of `setAuthenticationRequestContextConverter`
  1657. If you are calling `OpenSaml4AuthenticationReqeustFactory#setAuthenticationRequestContextConverter`, for example, like so:
  1658. ====
  1659. .Java
  1660. [source,java,role="primary"]
  1661. ----
  1662. @Bean
  1663. Saml2AuthenticationRequestFactory authenticationRequestFactory() {
  1664. OpenSaml4AuthenticationRequestFactory factory = new OpenSaml4AuthenticationRequestFactory();
  1665. factory.setAuthenticationRequestContextConverter((context) -> {
  1666. AuthnRequestBuilder authnRequestBuilder = ConfigurationService.get(XMLObjectProviderRegistry.class)
  1667. .getBuilderFactory().getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
  1668. IssuerBuilder issuerBuilder = ConfigurationService.get(XMLObjectProviderRegistry.class)
  1669. .getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
  1670. tring issuer = context.getIssuer();
  1671. String destination = context.getDestination();
  1672. String assertionConsumerServiceUrl = context.getAssertionConsumerServiceUrl();
  1673. String protocolBinding = context.getRelyingPartyRegistration().getAssertionConsumerServiceBinding().getUrn();
  1674. AuthnRequest auth = authnRequestBuilder.buildObject();
  1675. auth.setID("ARQ" + UUID.randomUUID().toString().substring(1));
  1676. auth.setIssueInstant(Instant.now());
  1677. auth.setForceAuthn(Boolean.TRUE);
  1678. auth.setIsPassive(Boolean.FALSE);
  1679. auth.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
  1680. Issuer iss = issuerBuilder.buildObject();
  1681. iss.setValue(issuer);
  1682. auth.setIssuer(iss);
  1683. auth.setDestination(destination);
  1684. auth.setAssertionConsumerServiceURL(assertionConsumerServiceUrl);
  1685. });
  1686. return factory;
  1687. }
  1688. ----
  1689. ====
  1690. to ensure that ForceAuthn is set to `true`, you can instead do:
  1691. ====
  1692. .Java
  1693. [source,java,role="primary"]
  1694. ----
  1695. @Bean
  1696. Saml2AuthenticationRequestResolver authenticationRequestResolver(RelyingPartyRegistrationResolver registrations) {
  1697. OpenSaml4AuthenticationRequestResolver reaolver = new OpenSaml4AuthenticationRequestResolver(registrations);
  1698. resolver.setAuthnRequestCustomizer((context) -> context.getAuthnRequest().setForceAuthn(Boolean.TRUE));
  1699. return resolver;
  1700. }
  1701. ----
  1702. ====
  1703. Also, since `setAuthnRequestCustomizer` has direct access to the `HttpServletRequest`, there is no need for a `Saml2AuthenticationRequestContextResolver`.
  1704. Simply use `setAuthnRequestCustomizer` to read directly from `HttpServletRequest` this information you need.
  1705. ==== Use `setAuthnRequestCustomizer` instead of `setProtocolBinding`
  1706. Instead of doing:
  1707. ====
  1708. .Java
  1709. [source,java,role="primary"]
  1710. ----
  1711. @Bean
  1712. Saml2AuthenticationRequestFactory authenticationRequestFactory() {
  1713. OpenSaml4AuthenticationRequestFactory factory = new OpenSaml4AuthenticationRequestFactory();
  1714. factory.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")
  1715. return factory;
  1716. }
  1717. ----
  1718. ====
  1719. you can do:
  1720. ====
  1721. .Java
  1722. [source,java,role="primary"]
  1723. ----
  1724. @Bean
  1725. Saml2AuthenticationRequestResolver authenticationRequestResolver() {
  1726. OpenSaml4AuthenticationRequestResolver reaolver = new OpenSaml4AuthenticationRequestResolver(registrations);
  1727. resolver.setAuthnRequestCustomizer((context) -> context.getAuthnRequest()
  1728. .setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"));
  1729. return resolver;
  1730. }
  1731. ----
  1732. ====
  1733. [NOTE]
  1734. ====
  1735. Since Spring Security only supports the `POST` binding for authentication, there is not very much value in overriding the protocol binding at this point in time.
  1736. ====
  1737. === Use the latest `Saml2AuthenticationToken` constructor
  1738. In an early release, `Saml2AuthenticationToken` took several individual settings as constructor parameters.
  1739. This created a challenge each time a new parameter needed to be added.
  1740. Since most of these settings were part of `RelyingPartyRegistration`, a new constructor was added where a `RelyingPartyRegistration` could be provided, making the constructor more stable.
  1741. It also is valuable in that it more closely aligns with the design of `OAuth2LoginAuthenticationToken`.
  1742. Most applications do not construct this class directly since `Saml2WebSsoAuthenticationFilter` does.
  1743. However, in the event that your application constructs one, please change from:
  1744. ====
  1745. .Java
  1746. [source,java,role="primary"]
  1747. ----
  1748. new Saml2AuthenticationToken(saml2Response, registration.getSingleSignOnServiceLocation(),
  1749. registration.getAssertingParty().getEntityId(), registration.getEntityId(), registration.getCredentials())
  1750. ----
  1751. .Kotlin
  1752. [source,kotlin,role="secondary"]
  1753. ----
  1754. Saml2AuthenticationToken(saml2Response, registration.getSingleSignOnServiceLocation(),
  1755. registration.getAssertingParty().getEntityId(), registration.getEntityId(), registration.getCredentials())
  1756. ----
  1757. ====
  1758. to:
  1759. ====
  1760. .Java
  1761. [source,java,role="primary"]
  1762. ----
  1763. new Saml2AuthenticationToken(saml2Response, registration)
  1764. ----
  1765. .Kotlin
  1766. [source,kotlin,role="secondary"]
  1767. ----
  1768. Saml2AuthenticationToken(saml2Response, registration)
  1769. ----
  1770. ====
  1771. === Use `RelyingPartyRegistration` updated methods
  1772. In an early release of Spring Security's SAML support, there was some ambiguity on the meaning of certain `RelyingPartyRegistration` methods and their function.
  1773. As more capabilities were added to `RelyingPartyRegistration`, it became necessary to clarify this ambiguity by changing method names to ones that aligned with spec language.
  1774. The deprecated methods in `RelyingPartyRegstration` are removed.
  1775. To prepare for that, consider the following representative usage of `RelyingPartyRegistration`:
  1776. ====
  1777. .Java
  1778. [source,java,role="primary"]
  1779. ----
  1780. String idpEntityId = registration.getRemoteIdpEntityId();
  1781. String assertionConsumerServiceUrl = registration.getAssertionConsumerServiceUrlTemplate();
  1782. String idpWebSsoUrl = registration.getIdpWebSsoUrl();
  1783. String localEntityId = registration.getLocalEntityIdTemplate();
  1784. List<Saml2X509Credential> verifying = registration.getCredentials().stream()
  1785. .filter(Saml2X509Credential::isSignatureVerficationCredential)
  1786. .collect(Collectors.toList());
  1787. ----
  1788. .Kotlin
  1789. [source,kotlin,role="secondary"]
  1790. ----
  1791. val idpEntityId: String = registration.getRemoteIdpEntityId()
  1792. val assertionConsumerServiceUrl: String = registration.getAssertionConsumerServiceUrlTemplate()
  1793. val idpWebSsoUrl: String = registration.getIdpWebSsoUrl()
  1794. val localEntityId: String = registration.getLocalEntityIdTemplate()
  1795. val verifying: List<Saml2X509Credential> = registration.getCredentials()
  1796. .filter(Saml2X509Credential::isSignatureVerficationCredential)
  1797. ----
  1798. ====
  1799. This should change to:
  1800. ====
  1801. .Java
  1802. [source,java,role="primary"]
  1803. ----
  1804. String assertingPartyEntityId = registration.getAssertingPartyDetails().getEntityId();
  1805. String assertionConsumerServiceLocation = registration.getAssertionConsumerServiceLocation();
  1806. String singleSignOnServiceLocation = registration.getAssertingPartyDetails().getSingleSignOnServiceLocation();
  1807. String entityId = registration.getEntityId();
  1808. List<Saml2X509Credential> verifying = registration.getAssertingPartyDetails().getVerificationX509Credentials();
  1809. ----
  1810. .Kotlin
  1811. [source,kotlin,role="secondary"]
  1812. ----
  1813. val assertingPartyEntityId: String = registration.getAssertingPartyDetails().getEntityId()
  1814. val assertionConsumerServiceLocation: String = registration.getAssertionConsumerServiceLocation()
  1815. val singleSignOnServiceLocation: String = registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()
  1816. val entityId: String = registration.getEntityId()
  1817. val verifying: List<Saml2X509Credential> = registration.getAssertingPartyDetails().getVerificationX509Credentials()
  1818. ----
  1819. ====
  1820. For a complete listing of all changed methods, please see {security-api-url}org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.html[``RelyingPartyRegistration``'s JavaDoc].
  1821. === Use OpenSAML 4
  1822. OpenSAML 3 has reached its end-of-life.
  1823. As such, Spring Security 6 drops support for it, bumping up its OpenSAML baseline to 4.
  1824. To prepare for the upgrade, update your pom to depend on OpenSAML 4 instead of 3:
  1825. ====
  1826. .Maven
  1827. [source,maven,role="primary"]
  1828. ----
  1829. <dependencyManagement>
  1830. <dependency>
  1831. <groupId>org.opensaml</groupId>
  1832. <artifactId>opensaml-core</artifactId>
  1833. <version>4.2.1</version>
  1834. </dependency>
  1835. <dependency>
  1836. <groupId>org.opensaml</groupId>
  1837. <artifactId>opensaml-saml-api</artifactId>
  1838. <version>4.2.1</version>
  1839. </dependency>
  1840. <dependency>
  1841. <groupId>org.opensaml</groupId>
  1842. <artifactId>opensaml-saml-impl</artifactId>
  1843. <version>4.2.1</version>
  1844. </dependency>
  1845. </dependencyManagement>
  1846. ----
  1847. .Gradle
  1848. [source,gradle,role="secondary"]
  1849. ----
  1850. dependencies {
  1851. constraints {
  1852. api "org.opensaml:opensaml-core:4.2.1"
  1853. api "org.opensaml:opensaml-saml-api:4.2.1"
  1854. api "org.opensaml:opensaml-saml-impl:4.2.1"
  1855. }
  1856. }
  1857. ----
  1858. ====
  1859. You must use at least OpenSAML 4.1.1 to update to Spring Security 6's SAML support.
  1860. === Use `OpenSaml4AuthenticationProvider`
  1861. In order to support both OpenSAML 3 and 4 at the same time, Spring Security released `OpenSamlAuthenticationProvider` and `OpenSaml4AuthenticationProvider`.
  1862. In 6.0, because OpenSAML3 support is removed, `OpenSamlAuthenticationProvider` is removed as well.
  1863. Not all methods in `OpenSamlAuthenticationProvider` were ported 1-to-1 to `OpenSaml4AuthenticationProvider`.
  1864. As such, some adjustment will be required to make the challenge.
  1865. Consider the following representative usage of `OpenSamlAuthenticationProvider`:
  1866. ====
  1867. .Java
  1868. [source,java,role="primary"]
  1869. ----
  1870. OpenSamlAuthenticationProvider versionThree = new OpenSamlAuthenticationProvider();
  1871. versionThree.setAuthoritiesExtractor(myAuthoritiesExtractor);
  1872. versionThree.setResponseTimeValidationSkew(myDuration);
  1873. ----
  1874. .Kotlin
  1875. [source,kotlin,role="secondary"]
  1876. ----
  1877. val versionThree: OpenSamlAuthenticationProvider = OpenSamlAuthenticationProvider()
  1878. versionThree.setAuthoritiesExtractor(myAuthoritiesExtractor)
  1879. versionThree.setResponseTimeValidationSkew(myDuration)
  1880. ----
  1881. ====
  1882. This should change to:
  1883. ====
  1884. .Java
  1885. [source,java,role="primary"]
  1886. ----
  1887. Converter<ResponseToken, Saml2Authentication> delegate = OpenSaml4AuthenticationProvider
  1888. .createDefaultResponseAuthenticationConverter();
  1889. OpenSaml4AuthenticationProvider versionFour = new OpenSaml4AuthenticationProvider();
  1890. versionFour.setResponseAuthenticationConverter((responseToken) -> {
  1891. Saml2Authentication authentication = delegate.convert(responseToken);
  1892. Assertion assertion = responseToken.getResponse().getAssertions().get(0);
  1893. AuthenticatedPrincipal principal = (AuthenticatedPrincipal) authentication.getPrincipal();
  1894. Collection<GrantedAuthority> authorities = myAuthoritiesExtractor.convert(assertion);
  1895. return new Saml2Authentication(principal, authentication.getSaml2Response(), authorities);
  1896. });
  1897. Converter<AssertionToken, Saml2ResponseValidationResult> validator = OpenSaml4AuthenticationProvider
  1898. .createDefaultAssertionValidatorWithParameters((p) -> p.put(CLOCK_SKEW, myDuration));
  1899. versionFour.setAssertionValidator(validator);
  1900. ----
  1901. .Kotlin
  1902. [source,kotlin,role="secondary"]
  1903. ----
  1904. val delegate = OpenSaml4AuthenticationProvider.createDefaultResponseAuthenticationConverter()
  1905. val versionFour = OpenSaml4AuthenticationProvider()
  1906. versionFour.setResponseAuthenticationConverter({
  1907. responseToken -> {
  1908. val authentication = delegate.convert(responseToken)
  1909. val assertion = responseToken.getResponse().getAssertions().get(0)
  1910. val principal = (AuthenticatedPrincipal) authentication.getPrincipal()
  1911. val authorities = myAuthoritiesExtractor.convert(assertion)
  1912. return Saml2Authentication(principal, authentication.getSaml2Response(), authorities)
  1913. }
  1914. })
  1915. val validator = OpenSaml4AuthenticationProvider
  1916. .createDefaultAssertionValidatorWithParameters({ p -> p.put(CLOCK_SKEW, myDuration) })
  1917. versionFour.setAssertionValidator(validator)
  1918. ----
  1919. ====
  1920. [[use-new-requestmatchers]]
  1921. === Use the new `requestMatchers` methods
  1922. In Spring Security 5.8, the {security-api-url}org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.html#antMatchers(java.lang.String...)[`antMatchers`], {security-api-url}org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.html#mvcMatchers(java.lang.String...)[`mvcMatchers`], and {security-api-url}org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.html#regexMatchers(java.lang.String...)[`regexMatchers`] methods were deprecated in favor of new xref::servlet/authorization/authorize-http-requests.adoc#_request_matchers[`requestMatchers` methods].
  1923. The new `requestMatchers` methods were added xref::servlet/authorization/authorize-http-requests.adoc[to `authorizeHttpRequests`], `authorizeRequests`, CSRF configuration, `WebSecurityCustomizer` and any other places that had the specialized `RequestMatcher` methods.
  1924. The deprecated methods are removed in Spring Security 6.
  1925. These new methods have more secure defaults since they choose the most appropriate `RequestMatcher` implementation for your application.
  1926. In summary, the new methods choose the `MvcRequestMatcher` implementation if your application has Spring MVC in the classpath, falling back to the `AntPathRequestMatcher` implementation if Spring MVC is not present (aligning the behavior with the Kotlin equivalent methods).
  1927. To start using the new methods, you can replace the deprecated methods with the new ones. For example, the following application configuration:
  1928. ====
  1929. .Java
  1930. [source,java,role="primary"]
  1931. ----
  1932. @Configuration
  1933. @EnableWebSecurity
  1934. public class SecurityConfig {
  1935. @Bean
  1936. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  1937. http
  1938. .authorizeHttpRequests((authz) -> authz
  1939. .antMatchers("/api/admin/**").hasRole("ADMIN")
  1940. .antMatchers("/api/user/**").hasRole("USER")
  1941. .anyRequest().authenticated()
  1942. );
  1943. return http.build();
  1944. }
  1945. }
  1946. ----
  1947. ====
  1948. can be changed to:
  1949. ====
  1950. .Java
  1951. [source,java,role="primary"]
  1952. ----
  1953. @Configuration
  1954. @EnableWebSecurity
  1955. public class SecurityConfig {
  1956. @Bean
  1957. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  1958. http
  1959. .authorizeHttpRequests((authz) -> authz
  1960. .requestMatchers("/api/admin/**").hasRole("ADMIN")
  1961. .requestMatchers("/api/user/**").hasRole("USER")
  1962. .anyRequest().authenticated()
  1963. );
  1964. return http.build();
  1965. }
  1966. }
  1967. ----
  1968. ====
  1969. If you have Spring MVC in the classpath and are using the `mvcMatchers` methods, you can replace it with the new methods and Spring Security will choose the `MvcRequestMatcher` implementation for you.
  1970. The following configuration:
  1971. ====
  1972. .Java
  1973. [source,java,role="primary"]
  1974. ----
  1975. @Configuration
  1976. @EnableWebSecurity
  1977. @EnableWebMvc
  1978. public class SecurityConfig {
  1979. @Bean
  1980. SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  1981. http
  1982. .authorizeHttpRequests((authz) -> authz
  1983. .mvcMatchers("/admin/**").hasRole("ADMIN")
  1984. .anyRequest().authenticated()
  1985. );
  1986. return http.build();
  1987. }
  1988. }
  1989. ----
  1990. ====
  1991. is equivalent to:
  1992. ====
  1993. .Java
  1994. [source,java,role="primary"]
  1995. ----
  1996. @Configuration
  1997. @EnableWebSecurity
  1998. @EnableWebMvc
  1999. public class SecurityConfig {
  2000. @Bean
  2001. SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  2002. http
  2003. .authorizeHttpRequests((authz) -> authz
  2004. .requestMatchers("/admin/**").hasRole("ADMIN")
  2005. .anyRequest().authenticated()
  2006. );
  2007. return http.build();
  2008. }
  2009. }
  2010. ----
  2011. ====
  2012. If you are customizing the `servletPath` property of the `MvcRequestMatcher`, you can now use the `MvcRequestMatcher.Builder` to create `MvcRequestMatcher` instances that share the same servlet path:
  2013. ====
  2014. .Java
  2015. [source,java,role="primary"]
  2016. ----
  2017. @Configuration
  2018. @EnableWebSecurity
  2019. @EnableWebMvc
  2020. public class SecurityConfig {
  2021. @Bean
  2022. SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  2023. http
  2024. .authorizeHttpRequests((authz) -> authz
  2025. .mvcMatchers("/admin").servletPath("/path").hasRole("ADMIN")
  2026. .mvcMatchers("/user").servletPath("/path").hasRole("USER")
  2027. .anyRequest().authenticated()
  2028. );
  2029. return http.build();
  2030. }
  2031. }
  2032. ----
  2033. ====
  2034. The code above can be rewritten using the `MvcRequestMatcher.Builder` and the `requestMatchers` method:
  2035. ====
  2036. .Java
  2037. [source,java,role="primary"]
  2038. ----
  2039. @Configuration
  2040. @EnableWebSecurity
  2041. @EnableWebMvc
  2042. public class SecurityConfig {
  2043. @Bean
  2044. SecurityFilterChain securityFilterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
  2045. MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector).servletPath("/path");
  2046. http
  2047. .authorizeHttpRequests((authz) -> authz
  2048. .requestMatchers(mvcMatcherBuilder.pattern("/admin")).hasRole("ADMIN")
  2049. .requestMatchers(mvcMatcherBuilder.pattern("/user")).hasRole("USER")
  2050. .anyRequest().authenticated()
  2051. );
  2052. return http.build();
  2053. }
  2054. }
  2055. ----
  2056. ====
  2057. If you are having problem with the new `requestMatchers` methods, you can always switch back to the `RequestMatcher` implementation that you were using.
  2058. For example, if you still want to use `AntPathRequestMatcher` and `RegexRequestMatcher` implementations, you can use the `requestMatchers` method that accepts a `RequestMatcher` instance:
  2059. ====
  2060. .Java
  2061. [source,java,role="primary"]
  2062. ----
  2063. import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher;
  2064. import static org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher;
  2065. @Configuration
  2066. @EnableWebSecurity
  2067. public class SecurityConfig {
  2068. @Bean
  2069. SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  2070. http
  2071. .authorizeHttpRequests((authz) -> authz
  2072. .requestMatchers(antMatcher("/user/**")).hasRole("USER")
  2073. .requestMatchers(antMatcher(HttpMethod.POST, "/user/**")).hasRole("ADMIN")
  2074. .requestMatchers(regexMatcher(".*\\?x=y")).hasRole("SPECIAL") // matches /any/path?x=y
  2075. .anyRequest().authenticated()
  2076. );
  2077. return http.build();
  2078. }
  2079. }
  2080. ----
  2081. ====
  2082. Note that the above sample uses static factory methods from {security-api-url}org/springframework/security/web/util/matcher/AntPathRequestMatcher.html[`AntPathRequestMatcher`] and {security-api-url}org/springframework/security/web/util/matcher/RegexRequestMatcher.html[`RegexRequestMatcher`] to improve readability.
  2083. If you are using the `WebSecurityCustomizer` interface, you can replace the deprecated `antMatchers` methods:
  2084. ====
  2085. .Java
  2086. [source,java,role="primary"]
  2087. ----
  2088. @Bean
  2089. public WebSecurityCustomizer webSecurityCustomizer() {
  2090. return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2");
  2091. }
  2092. ----
  2093. ====
  2094. with their `requestMatchers` counterparts:
  2095. ====
  2096. .Java
  2097. [source,java,role="primary"]
  2098. ----
  2099. @Bean
  2100. public WebSecurityCustomizer webSecurityCustomizer() {
  2101. return (web) -> web.ignoring().requestMatchers("/ignore1", "/ignore2");
  2102. }
  2103. ----
  2104. ====
  2105. The same way, if you are customizing the CSRF configuration to ignore some paths, you can replace the deprecated methods with the `requestMatchers` methods:
  2106. ====
  2107. .Java
  2108. [source,java,role="primary"]
  2109. ----
  2110. @Bean
  2111. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  2112. http
  2113. .csrf((csrf) -> csrf
  2114. .ignoringAntMatchers("/no-csrf")
  2115. );
  2116. return http.build();
  2117. }
  2118. ----
  2119. ====
  2120. can be changed to:
  2121. ====
  2122. .Java
  2123. [source,java,role="primary"]
  2124. ----
  2125. @Bean
  2126. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  2127. http
  2128. .csrf((csrf) -> csrf
  2129. .ignoringRequestMatchers("/no-csrf")
  2130. );
  2131. return http.build();
  2132. }
  2133. ----
  2134. ====
  2135. [[use-new-security-matchers]]
  2136. === Use the new `securityMatchers` methods
  2137. In Spring Security 5.8, the `antMatchers`, `mvcMatchers` and `requestMatchers` methods from `HttpSecurity` were deprecated in favor of new `securityMatchers` methods.
  2138. Note that these methods are not the same from `authorizeHttpRequests` methods <<use-new-requestmatchers,which were deprecated>> in favor of the `requestMatchers` methods.
  2139. However, the `securityMatchers` methods are similar to the `requestMatchers` methods in the sense that they will choose the most appropriate `RequestMatcher` implementation for your application.
  2140. In summary, the new methods choose the `MvcRequestMatcher` implementation if your application has Spring MVC in the classpath, falling back to the `AntPathRequestMatcher` implementation if Spring MVC is not present (aligning the behavior with the Kotlin equivalent methods).
  2141. Another reason for adding the `securityMatchers` methods is to avoid confusion with the `requestMatchers` methods from `authorizeHttpRequests`.
  2142. The following configuration:
  2143. ====
  2144. .Java
  2145. [source,java,role="primary"]
  2146. ----
  2147. @Bean
  2148. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  2149. http
  2150. .antMatcher("/api/**", "/app/**")
  2151. .authorizeHttpRequests((authz) -> authz
  2152. .requestMatchers("/api/admin/**").hasRole("ADMIN")
  2153. .anyRequest().authenticated()
  2154. );
  2155. return http.build();
  2156. }
  2157. ----
  2158. ====
  2159. can be rewritten using the `securityMatchers` methods:
  2160. ====
  2161. .Java
  2162. [source,java,role="primary"]
  2163. ----
  2164. @Bean
  2165. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  2166. http
  2167. .securityMatcher("/api/**", "/app/**")
  2168. .authorizeHttpRequests((authz) -> authz
  2169. .requestMatchers("/api/admin/**").hasRole("ADMIN")
  2170. .anyRequest().authenticated()
  2171. );
  2172. return http.build();
  2173. }
  2174. ----
  2175. ====
  2176. If you are using a custom `RequestMatcher` in your `HttpSecurity` configuration:
  2177. ====
  2178. .Java
  2179. [source,java,role="primary"]
  2180. ----
  2181. @Bean
  2182. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  2183. http
  2184. .requestMatcher(new MyCustomRequestMatcher())
  2185. .authorizeHttpRequests((authz) -> authz
  2186. .requestMatchers("/api/admin/**").hasRole("ADMIN")
  2187. .anyRequest().authenticated()
  2188. );
  2189. return http.build();
  2190. }
  2191. public class MyCustomRequestMatcher implements RequestMatcher {
  2192. // ...
  2193. }
  2194. ----
  2195. ====
  2196. you can do the same using `securityMatcher`:
  2197. ====
  2198. .Java
  2199. [source,java,role="primary"]
  2200. ----
  2201. @Bean
  2202. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  2203. http
  2204. .securityMatcher(new MyCustomRequestMatcher())
  2205. .authorizeHttpRequests((authz) -> authz
  2206. .requestMatchers("/api/admin/**").hasRole("ADMIN")
  2207. .anyRequest().authenticated()
  2208. );
  2209. return http.build();
  2210. }
  2211. public class MyCustomRequestMatcher implements RequestMatcher {
  2212. // ...
  2213. }
  2214. ----
  2215. ====
  2216. If you are combining multiple `RequestMatcher` implementations in your `HttpSecurity` configuration:
  2217. ====
  2218. .Java
  2219. [source,java,role="primary"]
  2220. ----
  2221. @Bean
  2222. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  2223. http
  2224. .requestMatchers((matchers) -> matchers
  2225. .antMatchers("/api/**", "/app/**")
  2226. .mvcMatchers("/admin/**")
  2227. .requestMatchers(new MyCustomRequestMatcher())
  2228. )
  2229. .authorizeHttpRequests((authz) -> authz
  2230. .requestMatchers("/admin/**").hasRole("ADMIN")
  2231. .anyRequest().authenticated()
  2232. );
  2233. return http.build();
  2234. }
  2235. ----
  2236. ====
  2237. you can change it by using `securityMatchers`:
  2238. ====
  2239. .Java
  2240. [source,java,role="primary"]
  2241. ----
  2242. @Bean
  2243. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  2244. http
  2245. .securityMatchers((matchers) -> matchers
  2246. .requestMatchers("/api/**", "/app/**", "/admin/**")
  2247. .requestMatchers(new MyCustomRequestMatcher())
  2248. )
  2249. .authorizeHttpRequests((authz) -> authz
  2250. .requestMatchers("/admin/**").hasRole("ADMIN")
  2251. .anyRequest().authenticated()
  2252. );
  2253. return http.build();
  2254. }
  2255. ----
  2256. ====
  2257. If you are having problems with the `securityMatchers` methods choosing the `RequestMatcher` implementation for you, you can always choose the `RequestMatcher` implementation yourself:
  2258. ====
  2259. .Java
  2260. [source,java,role="primary"]
  2261. ----
  2262. import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher;
  2263. @Bean
  2264. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  2265. http
  2266. .securityMatcher(antMatcher("/api/**"), antMatcher("/app/**"))
  2267. .authorizeHttpRequests((authz) -> authz
  2268. .requestMatchers(antMatcher("/api/admin/**")).hasRole("ADMIN")
  2269. .anyRequest().authenticated()
  2270. );
  2271. return http.build();
  2272. }
  2273. ----
  2274. ====
  2275. === Stop using `Encryptors.queryableText`
  2276. `Encryptors.queryableText(CharSequence,CharSequence)` is unsafe since https://tanzu.vmware.com/security/cve-2020-5408[the same input data will produce the same output].
  2277. It was deprecated and will be removed in 6.0; Spring Security no longer supports encrypting data in this way.
  2278. To upgrade, you will either need to re-encrypt with a supported mechanism or store it decrypted.
  2279. Consider the following pseudocode for reading each encrypted entry from a table, decrypting it, and then re-encrypting it using a supported mechanism:
  2280. ====
  2281. .Java
  2282. [source,java,role="primary"]
  2283. ----
  2284. TextEncryptor deprecated = Encryptors.queryableText(password, salt);
  2285. BytesEncryptor aes = new AesBytesEncryptor(password, salt, KeyGenerators.secureRandom(12), CipherAlgorithm.GCM);
  2286. TextEncryptor supported = new HexEncodingTextEncryptor(aes);
  2287. for (MyEntry entry : entries) {
  2288. String value = deprecated.decrypt(entry.getEncryptedValue()); <1>
  2289. entry.setEncryptedValue(supported.encrypt(value)); <2>
  2290. entryService.save(entry)
  2291. }
  2292. ----
  2293. ====
  2294. <1> - The above uses the deprecated `queryableText` to convert the value to plaintext.
  2295. <2> - Then, the value is re-encrypted with a supported Spring Security mechanism.
  2296. Please see the reference manual for more information on what xref:features/integrations/cryptography.adoc[encryption mechanisms Spring Security supports].
  2297. == Reactive
  2298. === Use `AuthorizationManager` for Method Security
  2299. 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.
  2300. Should you run into trouble with making these changes, you can follow the
  2301. <<reactive-authorizationmanager-methods-opt-out,opt out steps>> at the end of this section.
  2302. 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.
  2303. [[reactive-change-to-useauthorizationmanager]]
  2304. ==== Change `useAuthorizationManager` to `true`
  2305. To opt in, change `useAuthorizationManager` to `true` like so:
  2306. ====
  2307. .Java
  2308. [source,java,role="primary"]
  2309. ----
  2310. @EnableReactiveMethodSecurity
  2311. ----
  2312. .Kotlin
  2313. [source,kotlin,role="secondary"]
  2314. ----
  2315. @EnableReactiveMethodSecurity
  2316. ----
  2317. ====
  2318. changes to:
  2319. ====
  2320. .Java
  2321. [source,java,role="primary"]
  2322. ----
  2323. @EnableReactiveMethodSecurity(useAuthorizationManager = true)
  2324. ----
  2325. .Kotlin
  2326. [source,kotlin,role="secondary"]
  2327. ----
  2328. @EnableReactiveMethodSecurity(useAuthorizationManager = true)
  2329. ----
  2330. ====
  2331. [[reactive-check-for-annotationconfigurationexceptions]]
  2332. ==== Check for ``AnnotationConfigurationException``s
  2333. `useAuthorizationManager` activates stricter enforcement of Spring Security's non-repeatable or otherwise incompatible annotations.
  2334. 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.
  2335. [[reactive-authorizationmanager-methods-opt-out]]
  2336. ==== Opt-out Steps
  2337. If you ran into trouble with `AuthorizationManager` for reactive method security, you can opt out by changing:
  2338. ====
  2339. .Java
  2340. [source,java,role="primary"]
  2341. ----
  2342. @EnableReactiveMethodSecurity
  2343. ----
  2344. .Kotlin
  2345. [source,kotlin,role="secondary"]
  2346. ----
  2347. @EnableReactiveMethodSecurity
  2348. ----
  2349. ====
  2350. to:
  2351. ====
  2352. .Java
  2353. [source,java,role="primary"]
  2354. ----
  2355. @EnableReactiveMethodSecurity(useAuthorizationManager = false)
  2356. ----
  2357. .Kotlin
  2358. [source,kotlin,role="secondary"]
  2359. ----
  2360. @EnableReactiveMethodSecurity(useAuthorizationManager = false)
  2361. ----
  2362. ====
  2363. === Propagate ``AuthenticationServiceException``s
  2364. {security-api-url}org/springframework/security/web/server/Webauthentication/AuthenticationWebFilter.html[`AuthenticationFilter`] propagates {security-api-url}org/springframework/security/authentication/AuthenticationServiceException.html[``AuthenticationServiceException``]s to the {security-api-url}org/springframework/security/web/server/ServerAuthenticationEntryPoint.html[`ServerAuthenticationEntryPoint`].
  2365. Because ``AuthenticationServiceException``s represent a server-side error instead of a client-side error, in 6.0, this changes to propagate them to the container.
  2366. ==== Configure `ServerAuthenticationFailureHandler` to rethrow ``AuthenticationServiceException``s
  2367. To prepare for the 6.0 default, `httpBasic` and `oauth2ResourceServer` should be configured to rethrow ``AuthenticationServiceException``s.
  2368. For each, construct the appropriate authentication entry point for `httpBasic` and for `oauth2ResourceServer`:
  2369. ====
  2370. .Java
  2371. [source,java,role="primary"]
  2372. ----
  2373. ServerAuthenticationEntryPoint bearerEntryPoint = new BearerTokenServerAuthenticationEntryPoint();
  2374. ServerAuthenticationEntryPoint basicEntryPoint = new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED);
  2375. ----
  2376. .Kotlin
  2377. [source,kotlin,role="secondary"]
  2378. ----
  2379. val bearerEntryPoint: ServerAuthenticationEntryPoint = BearerTokenServerAuthenticationEntryPoint()
  2380. val basicEntryPoint: ServerAuthenticationEntryPoint = HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED)
  2381. ----
  2382. ====
  2383. [NOTE]
  2384. ====
  2385. If you use a custom `AuthenticationEntryPoint` for either or both mechanisms, use that one instead for the remaining steps.
  2386. ====
  2387. Then, construct and configure a `ServerAuthenticationEntryPointFailureHandler` for each one:
  2388. ====
  2389. .Java
  2390. [source,java,role="primary"]
  2391. ----
  2392. AuthenticationFailureHandler bearerFailureHandler = new ServerAuthenticationEntryPointFailureHandler(bearerEntryPoint);
  2393. bearerFailureHandler.setRethrowAuthenticationServiceException(true);
  2394. AuthenticationFailureHandler basicFailureHandler = new ServerAuthenticationEntryPointFailureHandler(basicEntryPoint);
  2395. basicFailureHandler.setRethrowAuthenticationServiceException(true)
  2396. ----
  2397. .Kotlin
  2398. [source,kotlin,role="secondary"]
  2399. ----
  2400. val bearerFailureHandler: AuthenticationFailureHandler = ServerAuthenticationEntryPointFailureHandler(bearerEntryPoint)
  2401. bearerFailureHandler.setRethrowAuthenticationServiceException(true)
  2402. val basicFailureHandler: AuthenticationFailureHandler = ServerAuthenticationEntryPointFailureHandler(basicEntryPoint)
  2403. basicFailureHandler.setRethrowAuthenticationServiceException(true)
  2404. ----
  2405. ====
  2406. Finally, wire each authentication failure handler into the DSL, like so:
  2407. ====
  2408. .Java
  2409. [source,java,role="primary"]
  2410. ----
  2411. http
  2412. .httpBasic((basic) -> basic.authenticationFailureHandler(basicFailureHandler))
  2413. .oauth2ResourceServer((oauth2) -> oauth2.authenticationFailureHandler(bearerFailureHandler))
  2414. ----
  2415. .Kotlin
  2416. [source,kotlin,role="secondary"]
  2417. ----
  2418. http {
  2419. httpBasic {
  2420. authenticationFailureHandler = basicFailureHandler
  2421. }
  2422. oauth2ResourceServer {
  2423. authenticationFailureHandler = bearerFailureHandler
  2424. }
  2425. }
  2426. ----
  2427. ====
  2428. [[reactive-authenticationfailurehandler-opt-out]]
  2429. ==== Opt-out Steps
  2430. To opt-out of the 6.0 defaults and instead continue to pass `AuthenticationServiceException` on to ``ServerAuthenticationEntryPoint``s, you can follow the same steps as above, except set `rethrowAuthenticationServiceException` to false.