Skip to content

Commit

Permalink
Set maxAge correctly when expiring WebSession
Browse files Browse the repository at this point in the history
Closes gh-31214
  • Loading branch information
rstoyanchev committed Nov 8, 2023
1 parent 5df6e88 commit 5c012bb
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -105,20 +105,20 @@ public List<String> resolveSessionIds(ServerWebExchange exchange) {
@Override
public void setSessionId(ServerWebExchange exchange, String id) {
Assert.notNull(id, "'id' is required");
ResponseCookie cookie = initSessionCookie(exchange, id, getCookieMaxAge());
ResponseCookie cookie = initCookie(exchange, id).build();
exchange.getResponse().getCookies().set(this.cookieName, cookie);
}

@Override
public void expireSession(ServerWebExchange exchange) {
ResponseCookie cookie = initSessionCookie(exchange, "", Duration.ZERO);
ResponseCookie cookie = initCookie(exchange, "").maxAge(0).build();
exchange.getResponse().getCookies().set(this.cookieName, cookie);
}

private ResponseCookie initSessionCookie(ServerWebExchange exchange, String id, Duration maxAge) {
private ResponseCookie.ResponseCookieBuilder initCookie(ServerWebExchange exchange, String id) {
ResponseCookie.ResponseCookieBuilder builder = ResponseCookie.from(this.cookieName, id)
.path(exchange.getRequest().getPath().contextPath().value() + "/")
.maxAge(maxAge)
.maxAge(getCookieMaxAge())
.httpOnly(true)
.secure("https".equalsIgnoreCase(exchange.getRequest().getURI().getScheme()))
.sameSite("Lax");
Expand All @@ -127,7 +127,7 @@ private ResponseCookie initSessionCookie(ServerWebExchange exchange, String id,
this.initializer.accept(builder);
}

return builder.build();
return builder;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,15 @@ public void cookieInitializer() {
assertCookieValue("SESSION=123; Path=/; Domain=example.org; HttpOnly; SameSite=Strict");
}

@Test
public void expireSessionWhenMaxAgeSetViaInitializer() {
this.resolver.addCookieInitializer(builder -> builder.maxAge(600));
this.resolver.expireSession(this.exchange);

assertCookieValue("SESSION=; Path=/; Max-Age=0; " +
"Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; HttpOnly; SameSite=Lax");
}

private void assertCookieValue(String expected) {
MultiValueMap<String, ResponseCookie> cookies = this.exchange.getResponse().getCookies();
assertThat(cookies).hasSize(1);
Expand Down

0 comments on commit 5c012bb

Please sign in to comment.