Skip to content

Commit 66f81da

Browse files
committed
Throw exception if session created after response
Closes gh-1798
1 parent 829b62b commit 66f81da

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

spring-session-core/src/main/java/org/springframework/session/web/http/SessionRepositoryFilter.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,10 @@ public HttpSessionWrapper getSession(boolean create) {
309309
if (!create) {
310310
return null;
311311
}
312+
if (SessionRepositoryFilter.this.httpSessionIdResolver instanceof CookieHttpSessionIdResolver
313+
&& this.response.isCommitted()) {
314+
throw new IllegalStateException("Cannot create a session after the response has been committed");
315+
}
312316
if (SESSION_LOGGER.isDebugEnabled()) {
313317
SESSION_LOGGER.debug(
314318
"A new session was created. To help you troubleshoot where the session was created we provided a StackTrace (this is not an error). You can prevent this from appearing by disabling DEBUG logging for "

spring-session-core/src/test/java/org/springframework/session/web/http/SessionRepositoryFilterTests.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
import static org.assertj.core.api.Assertions.assertThat;
6363
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
6464
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
65+
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
6566
import static org.assertj.core.api.Assertions.fail;
6667
import static org.mockito.ArgumentMatchers.any;
6768
import static org.mockito.ArgumentMatchers.anyString;
@@ -423,6 +424,18 @@ public void doFilter(HttpServletRequest wrappedRequest) {
423424
assertThat(this.response.getCookie("SESSION")).isNotNull();
424425
}
425426

427+
@Test
428+
void doFilterGetSessionNewWhenResponseCommittedThenException() {
429+
assertThatIllegalStateException().isThrownBy(() -> doFilter(new DoInFilter() {
430+
@Override
431+
public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse)
432+
throws IOException {
433+
wrappedResponse.getWriter().flush();
434+
wrappedRequest.getSession();
435+
}
436+
}));
437+
}
438+
426439
@Test
427440
void doFilterGetSessionNew() throws Exception {
428441
doFilter(new DoInFilter() {

0 commit comments

Comments
 (0)