migration.adoc 98 KB

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