migration.adoc 100 KB

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