migration.adoc 97 KB

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