@@ -136,12 +136,7 @@ public void saveContext(SecurityContext context, HttpServletRequest request, Htt
136136 SaveContextOnUpdateOrErrorResponseWrapper .class );
137137 Assert .state (responseWrapper != null , () -> "Cannot invoke saveContext on response " + response
138138 + ". You must use the HttpRequestResponseHolder.response after invoking loadContext" );
139- // saveContext() might already be called by the response wrapper if something in
140- // the chain called sendError() or sendRedirect(). This ensures we only call it
141- // once per request.
142- if (!responseWrapper .isContextSaved ()) {
143- responseWrapper .saveContext (context );
144- }
139+ responseWrapper .saveContext (context );
145140 }
146141
147142 @ Override
@@ -296,6 +291,8 @@ final class SaveToSessionResponseWrapper extends SaveContextOnUpdateOrErrorRespo
296291
297292 private final Authentication authBeforeExecution ;
298293
294+ private boolean isSaveContextInvoked ;
295+
299296 /**
300297 * Takes the parameters required to call <code>saveContext()</code> successfully
301298 * in addition to the request and the response object we are wrapping.
@@ -339,6 +336,7 @@ protected void saveContext(SecurityContext context) {
339336 // SEC-1587 A non-anonymous context may still be in the session
340337 // SEC-1735 remove if the contextBeforeExecution was not anonymous
341338 httpSession .removeAttribute (springSecurityContextKey );
339+ this .isSaveContextInvoked = true ;
342340 }
343341 if (this .logger .isDebugEnabled ()) {
344342 if (authentication == null ) {
@@ -358,6 +356,7 @@ protected void saveContext(SecurityContext context) {
358356 // is set SEC-1561
359357 if (contextChanged (context ) || httpSession .getAttribute (springSecurityContextKey ) == null ) {
360358 httpSession .setAttribute (springSecurityContextKey , context );
359+ this .isSaveContextInvoked = true ;
361360 if (this .logger .isDebugEnabled ()) {
362361 this .logger .debug (LogMessage .format ("Stored %s to HttpSession [%s]" , context , httpSession ));
363362 }
@@ -366,7 +365,8 @@ protected void saveContext(SecurityContext context) {
366365 }
367366
368367 private boolean contextChanged (SecurityContext context ) {
369- return context != this .contextBeforeExecution || context .getAuthentication () != this .authBeforeExecution ;
368+ return this .isSaveContextInvoked || context != this .contextBeforeExecution
369+ || context .getAuthentication () != this .authBeforeExecution ;
370370 }
371371
372372 private HttpSession createNewSessionIfAllowed (SecurityContext context ) {
0 commit comments