migration.adoc 105 KB

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