[rest] TokenResource: Set SameSite attribute for session id cookie (#4160)

* [rest] TokenResource: Properly set SameSite attribute for session id cookie

Fixes #4159.

Signed-off-by: Florian Hotze <florianh_dev@icloud.com>
pull/4157/head^2
Florian Hotze 2024-03-27 22:31:29 +01:00 committed by GitHub
parent 7f47d825a0
commit e871dcfa47
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 9 additions and 7 deletions

View File

@ -33,7 +33,6 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
@ -95,6 +94,8 @@ public class TokenResource implements RESTResource {
/** The name of the HTTP-only cookie holding the session ID */
public static final String SESSIONID_COOKIE_NAME = "X-OPENHAB-SESSIONID";
private static final String SESSIONID_COOKIE_FORMAT = SESSIONID_COOKIE_NAME
+ "=%s; Domain=%s; Path=/; Max-Age=2147483647; HttpOnly; SameSite=Strict";
/** The default lifetime of tokens in minutes before they expire */
public static final int TOKEN_LIFETIME = 60;
@ -244,9 +245,10 @@ public class TokenResource implements RESTResource {
if (sessionCookie != null && sessionCookie.getValue().equals(session.get().getSessionId())) {
try {
URI domainUri = new URI(session.get().getRedirectUri());
NewCookie newCookie = new NewCookie(SESSIONID_COOKIE_NAME, null, "/", domainUri.getHost(), null, 0,
false, true);
response.cookie(newCookie);
// workaround to set the SameSite cookie attribute until we upgrade to
// jakarta.ws.rs/jakarta.ws.rs-api/3.1.0 or newer
response.header("Set-Cookie",
SESSIONID_COOKIE_FORMAT.formatted(UUID.randomUUID(), domainUri.getHost()));
} catch (Exception e) {
}
}
@ -351,9 +353,9 @@ public class TokenResource implements RESTResource {
throw new IllegalArgumentException(
"Will not honor the request to set a session cookie for this client, because it's only allowed for root redirect URIs");
}
NewCookie newCookie = new NewCookie(SESSIONID_COOKIE_NAME, sessionId, "/", domainUri.getHost(), null,
2147483647, false, true);
response.cookie(newCookie);
// workaround to set the SameSite cookie attribute until we upgrade to
// jakarta.ws.rs/jakarta.ws.rs-api/3.1.0 or newer
response.header("Set-Cookie", SESSIONID_COOKIE_FORMAT.formatted(sessionId, domainUri.getHost()));
// also mark the session as supported by a cookie
newSession.setSessionCookie(true);