Skip to content

Commit 5c012bb

Browse files
committed
Set maxAge correctly when expiring WebSession
Closes gh-31214
1 parent 5df6e88 commit 5c012bb

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

spring-web/src/main/java/org/springframework/web/server/session/CookieWebSessionIdResolver.java

+5-5
Original file line numberDiff line numberDiff line change
@@ -105,20 +105,20 @@ public List<String> resolveSessionIds(ServerWebExchange exchange) {
105105
@Override
106106
public void setSessionId(ServerWebExchange exchange, String id) {
107107
Assert.notNull(id, "'id' is required");
108-
ResponseCookie cookie = initSessionCookie(exchange, id, getCookieMaxAge());
108+
ResponseCookie cookie = initCookie(exchange, id).build();
109109
exchange.getResponse().getCookies().set(this.cookieName, cookie);
110110
}
111111

112112
@Override
113113
public void expireSession(ServerWebExchange exchange) {
114-
ResponseCookie cookie = initSessionCookie(exchange, "", Duration.ZERO);
114+
ResponseCookie cookie = initCookie(exchange, "").maxAge(0).build();
115115
exchange.getResponse().getCookies().set(this.cookieName, cookie);
116116
}
117117

118-
private ResponseCookie initSessionCookie(ServerWebExchange exchange, String id, Duration maxAge) {
118+
private ResponseCookie.ResponseCookieBuilder initCookie(ServerWebExchange exchange, String id) {
119119
ResponseCookie.ResponseCookieBuilder builder = ResponseCookie.from(this.cookieName, id)
120120
.path(exchange.getRequest().getPath().contextPath().value() + "/")
121-
.maxAge(maxAge)
121+
.maxAge(getCookieMaxAge())
122122
.httpOnly(true)
123123
.secure("https".equalsIgnoreCase(exchange.getRequest().getURI().getScheme()))
124124
.sameSite("Lax");
@@ -127,7 +127,7 @@ private ResponseCookie initSessionCookie(ServerWebExchange exchange, String id,
127127
this.initializer.accept(builder);
128128
}
129129

130-
return builder.build();
130+
return builder;
131131
}
132132

133133
}

spring-web/src/test/java/org/springframework/web/server/session/CookieWebSessionIdResolverTests.java

+9
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,15 @@ public void cookieInitializer() {
5454
assertCookieValue("SESSION=123; Path=/; Domain=example.org; HttpOnly; SameSite=Strict");
5555
}
5656

57+
@Test
58+
public void expireSessionWhenMaxAgeSetViaInitializer() {
59+
this.resolver.addCookieInitializer(builder -> builder.maxAge(600));
60+
this.resolver.expireSession(this.exchange);
61+
62+
assertCookieValue("SESSION=; Path=/; Max-Age=0; " +
63+
"Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; HttpOnly; SameSite=Lax");
64+
}
65+
5766
private void assertCookieValue(String expected) {
5867
MultiValueMap<String, ResponseCookie> cookies = this.exchange.getResponse().getCookies();
5968
assertThat(cookies).hasSize(1);

0 commit comments

Comments
 (0)