Cookies
suggest changeHTTP is stateless: each request stands on its own. Cookies are how a server gets a browser (or any HTTP client) to remember something and send it back. The mechanism is just two headers:
HTTP/1.1 200 OK
Set-Cookie: session=k3J9xQ2v; Path=/; Secure; HttpOnly; SameSite=Lax
Set-Cookie: theme=dark; Path=/; Max-Age=31536000
GET /account HTTP/1.1
Cookie: session=k3J9xQ2v; theme=dark
- The server sends one
Set-Cookieheader per cookie. It holdsname=valuefollowed by attributes that control where, how long and over which connections the cookie is sent. - The client sends back all matching cookies in one
Cookieheader, asname=valuepairs separated by;. The attributes are not sent back. The server can't tell a cookie's path, expiry or flags from the request.
The JDK has no server-side cookie API outside of Servlets, so this article builds the Set-Cookie and Cookie handling for the built-in com.sun.net.httpserver.HttpServer by hand. It also covers the client side (java.net.CookieManager with java.net.http.HttpClient), signing cookies so they can't be forged, and the cookie APIs in Jakarta Servlet and Spring. Each example is a single file you can run with java Example.java. Servers bind to a free port (new InetSocketAddress("localhost", 0)). All output comes from JDK 25.
See A minimal HTTP server for the basics of HttpServer, HTTP headers for header handling in general and Sessions for server-side sessions built on top of cookies.
Cookie attributes
| Attribute | Meaning |
|---|---|
Path=/app |
Send only for URLs under /app. Defaults to the directory of the request URL, so always set it (usually to /) |
Domain=example.com |
Also send to subdomains (www.example.com, api.example.com). Without it the cookie goes only to the exact host that set it, which is safer |
Max-Age=3600 |
Lifetime in seconds. 0 or negative deletes the cookie |
Expires=Sun, 17 Oct 2027 20:17:30 GMT |
Older way to give a lifetime, as an absolute date. Max-Age wins when both are present |
Secure |
Send only over HTTPS (browsers make an exception for localhost) |
HttpOnly |
Hide from JavaScript (document.cookie). Use it for every session or auth cookie |
SameSite=Lax |
Strict: never sent on cross-site requests. Lax: sent on top-level navigation (clicking a link) but not on cross-site POST, fetch or <img>. None: always sent, requires Secure |
A cookie with neither Max-Age nor Expires is a session cookie: the browser drops it when it closes (although browsers that restore sessions keep it). Chrome treats a cookie without SameSite as Lax, but other browsers don't, so always set it explicitly.
Limits to keep in mind: about 4096 bytes per cookie (name, value and attributes together) and around 50 cookies per domain. Every cookie goes with every matching request, including requests for images and CSS, so keep them small. Store an ID in the cookie and the data on the server.
Setting cookies
A Set-Cookie header is a plain string, so on HttpServer you add it with getResponseHeaders().add(). Use add(), not set(): each cookie needs its own header, and set() replaces earlier values. Building the string by hand is error-prone, so here's a small builder:
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class SetCookies {
static final DateTimeFormatter HTTP_DATE =
DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
// Builds one Set-Cookie header value
static final class SetCookie {
private final String name, value;
private String path = "/", domain, sameSite;
private Duration maxAge;
private boolean secure, httpOnly;
SetCookie(String name, String value) { this.name = name; this.value = value; }
SetCookie path(String p) { path = p; return this; }
SetCookie domain(String d) { domain = d; return this; }
SetCookie maxAge(Duration d) { maxAge = d; return this; }
SetCookie secure() { secure = true; return this; }
SetCookie httpOnly() { httpOnly = true; return this; }
SetCookie sameSite(String s) { sameSite = s; return this; }
@Override public String toString() {
StringBuilder sb = new StringBuilder(name).append('=').append(value);
if (path != null) sb.append("; Path=").append(path);
if (domain != null) sb.append("; Domain=").append(domain);
if (maxAge != null) {
sb.append("; Max-Age=").append(maxAge.toSeconds());
// Expires is for very old clients; Max-Age wins when both are present
ZonedDateTime expires = ZonedDateTime.now(ZoneOffset.UTC).plus(maxAge);
sb.append("; Expires=").append(HTTP_DATE.format(expires));
}
if (secure) sb.append("; Secure");
if (httpOnly) sb.append("; HttpOnly");
if (sameSite != null) sb.append("; SameSite=").append(sameSite);
return sb.toString();
}
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/login", exchange -> {
var h = exchange.getResponseHeaders();
h.add("Set-Cookie", new SetCookie("session", "k3J9xQ2v")
.httpOnly().secure().sameSite("Lax").toString());
h.add("Set-Cookie", new SetCookie("theme", "dark")
.maxAge(Duration.ofDays(365)).sameSite("Lax").toString());
exchange.sendResponseHeaders(204, -1);
exchange.close();
});
server.start();
HttpClient client = HttpClient.newHttpClient();
URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/login");
HttpResponse<Void> resp = client.send(HttpRequest.newBuilder(uri).build(),
HttpResponse.BodyHandlers.discarding());
resp.headers().allValues("Set-Cookie").forEach(System.out::println);
server.stop(0);
}
}
Output:
session=k3J9xQ2v; Path=/; Secure; HttpOnly; SameSite=Lax
theme=dark; Path=/; Max-Age=31536000; Expires=Sun, 17 Oct 2027 20:18:52 GMT; SameSite=Lax
The builder writes Expires in addition to Max-Age when there's a lifetime. Modern browsers only need Max-Age, but as the next sections show, the JDK's own cookie parser treats a cookie with Max-Age and no Expires differently. The date must be in English and in GMT, so the formatter uses Locale.US, whatever the default locale of the server is.
Don't use
java.net.HttpCookie.toString()to produceSet-Cookieheaders. It writes the obsolete RFC 2965 format (session="abc";$Path="/") and leaves outMax-Age,SecureandHttpOnly.HttpCookieis meant for the client side.
Reading cookies
All cookies arrive in the Cookie request header. HTTP/1.1 clients send one such header, but HTTP/2 clients may split it into several, so parse every value. The format is simple, name=value pairs separated by ;, but the input comes from the client and can be anything, so skip what doesn't parse:
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.CookieManager;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class ReadCookies {
// Parses all Cookie request headers into name -> value
static Map<String, String> parseCookies(Headers headers) {
Map<String, String> cookies = new LinkedHashMap<>();
for (String header : headers.getOrDefault("Cookie", List.of())) {
for (String pair : header.split(";")) {
int eq = pair.indexOf('=');
if (eq <= 0) continue; // skip malformed pairs
String name = pair.substring(0, eq).trim();
if (name.startsWith("$")) continue; // RFC 2965 attributes, not cookies
String value = pair.substring(eq + 1).trim();
if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) {
value = value.substring(1, value.length() - 1);
}
cookies.putIfAbsent(name, value); // first one wins
}
}
return cookies;
}
static void send(HttpExchange ex, String text) throws IOException {
byte[] body = text.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
ex.sendResponseHeaders(200, body.length);
try (var out = ex.getResponseBody()) { out.write(body); }
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/", ex -> {
Map<String, String> cookies = parseCookies(ex.getRequestHeaders());
int visits = 0;
try {
visits = Integer.parseInt(cookies.getOrDefault("visits", "0"));
} catch (NumberFormatException e) {
// the client can send anything; treat garbage as a new visitor
}
visits++;
ex.getResponseHeaders().add("Set-Cookie",
"visits=" + visits + "; Path=/; Max-Age=86400; HttpOnly; SameSite=Lax");
send(ex, "cookies=" + cookies + " -> visit #" + visits);
});
server.start();
String base = "http://localhost:" + server.getAddress().getPort();
HttpClient client = HttpClient.newBuilder().cookieHandler(new CookieManager()).build();
for (int i = 0; i < 3; i++) {
var req = HttpRequest.newBuilder(URI.create(base + "/")).build();
System.out.println(client.send(req, HttpResponse.BodyHandlers.ofString()).body());
}
// A hand-written Cookie header with several pairs and junk in it
var req = HttpRequest.newBuilder(URI.create(base + "/"))
.header("Cookie", "theme=dark; visits=abc; ;novalue; lang=\"pl\"")
.build();
System.out.println(HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString()).body());
server.stop(0);
}
}
Output:
cookies={} -> visit #1
cookies={visits=1} -> visit #2
cookies={visits=2} -> visit #3
cookies={theme=dark, visits=abc, lang=pl} -> visit #1
Things to note:
- When the same name appears twice the parser keeps the first. Browsers can store two cookies with the same name but different paths (or domains) and send both, ordered by path length, the most specific first. The request doesn't say which is which, which is another reason to always use
Path=/. visits=abcwas handled without an exception. Treat every cookie value as untrusted input. The user can edit cookies in the browser's developer tools as easily as a form field.- Don't use
HttpCookie.parse()for theCookieheader. It parsesSet-Cookievalues and returns only the first pair:HttpCookie.parse("a=1; b=2")gives[a=1]. - The parser skips names that start with
$. The next section explains where they come from.
The JDK version quirk
HttpCookie.parse() guesses which spec a Set-Cookie header follows. If the header has Max-Age but no Expires, it decides it's an RFC 2965 (version 1) cookie, and CookieManager then sends it back in that old format with $Version, $Path and $Domain pairs and quoted values:
import com.sun.net.httpserver.HttpServer;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class VersionQuirk {
public static void main(String[] args) throws Exception {
String[] setCookies = {
"a=1; Path=/",
"b=2; Path=/; Max-Age=600",
"c=3; Path=/; Max-Age=600; Expires=Wed, 21 Oct 2037 07:28:00 GMT",
};
for (String sc : setCookies) {
System.out.printf("%-65s version=%d%n", sc, HttpCookie.parse(sc).get(0).getVersion());
}
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/", ex -> {
if (ex.getRequestURI().getPath().equals("/set")) {
for (String sc : setCookies) ex.getResponseHeaders().add("Set-Cookie", sc);
} else {
System.out.println("Cookie: " + ex.getRequestHeaders().get("Cookie"));
}
ex.sendResponseHeaders(204, -1);
ex.close();
});
server.start();
String base = "http://localhost:" + server.getAddress().getPort();
HttpClient client = HttpClient.newBuilder().cookieHandler(new CookieManager()).build();
for (String path : new String[] {"/set", "/show"}) {
client.send(HttpRequest.newBuilder(URI.create(base + path)).build(),
HttpResponse.BodyHandlers.discarding());
}
server.stop(0);
}
}
Output:
a=1; Path=/ version=0
b=2; Path=/; Max-Age=600 version=1
c=3; Path=/; Max-Age=600; Expires=Wed, 21 Oct 2037 07:28:00 GMT version=0
Cookie: [$Version="1"; b="2";$Path="/";$Domain="localhost.local"; a=1; c=3]
Browsers never do this, and no server expects it. If your server is called by Java clients that use CookieManager (including your own integration tests), either send Expires together with Max-Age, as the builder above does, or make the server's parser ignore $ names and strip quotes.
Deleting cookies
There's no "delete" header. To remove a cookie the server sets it again with Max-Age=0 (and an Expires date in the past for old clients). The name, Path and Domain must match the original cookie exactly. Otherwise the client treats it as a different cookie and the original stays:
import com.sun.net.httpserver.HttpServer;
import java.net.CookieManager;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class DeleteCookies {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/app/login", ex -> {
ex.getResponseHeaders().add("Set-Cookie", "session=abc; Path=/app; HttpOnly");
ex.sendResponseHeaders(204, -1);
ex.close();
});
server.createContext("/app/logout-wrong", ex -> {
// Path doesn't match the original cookie, so this creates a second cookie
// with Path=/ and then removes it; /app's session cookie survives
ex.getResponseHeaders().add("Set-Cookie", "session=; Path=/; Max-Age=0");
ex.sendResponseHeaders(204, -1);
ex.close();
});
server.createContext("/app/logout", ex -> {
ex.getResponseHeaders().add("Set-Cookie",
"session=; Path=/app; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly");
ex.sendResponseHeaders(204, -1);
ex.close();
});
server.start();
String base = "http://localhost:" + server.getAddress().getPort();
CookieManager manager = new CookieManager();
HttpClient client = HttpClient.newBuilder().cookieHandler(manager).build();
for (String path : new String[] {"/app/login", "/app/logout-wrong", "/app/logout"}) {
client.send(HttpRequest.newBuilder(URI.create(base + path)).build(),
HttpResponse.BodyHandlers.discarding());
System.out.printf("after %-18s store: %s%n", path, manager.getCookieStore().getCookies());
}
server.stop(0);
}
}
Output:
after /app/login store: [session=abc]
after /app/logout-wrong store: [session=abc]
after /app/logout store: []
The same goes for changing a cookie: send it again with the same name, path and domain and the new value replaces the old one.
Encoding cookie values
A cookie value may contain only printable ASCII without spaces, double quotes, commas, semicolons and backslashes. Anything else must be encoded. Here's what happens without encoding and two common ways to encode:
import java.net.HttpCookie;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class CookieValues {
public static void main(String[] args) {
String raw = "Zażółć; city=Kraków, PL";
// Unencoded: the ';' ends the value, everything after it looks like attributes
HttpCookie broken = HttpCookie.parse("note=" + raw).get(0);
System.out.println("raw: value=" + broken.getValue());
// Option 1: percent-encoding (readable, a bit longer)
String url = URLEncoder.encode(raw, StandardCharsets.UTF_8);
System.out.println("url: " + url);
System.out.println("decoded: " + URLDecoder.decode(url, StandardCharsets.UTF_8));
// Option 2: Base64url without padding (opaque, safe for any bytes)
String b64 = Base64.getUrlEncoder().withoutPadding()
.encodeToString(raw.getBytes(StandardCharsets.UTF_8));
System.out.println("base64: " + b64);
System.out.println("decoded: " + new String(Base64.getUrlDecoder().decode(b64), StandardCharsets.UTF_8));
}
}
Output:
raw: value=Zażółć
url: Za%C5%BC%C3%B3%C5%82%C4%87%3B+city%3DKrak%C3%B3w%2C+PL
decoded: Zażółć; city=Kraków, PL
base64: WmHFvMOzxYLEhzsgY2l0eT1LcmFrw7N3LCBQTA
decoded: Zażółć; city=Kraków, PL
Without encoding the ; ended the value, and the rest was parsed as attributes. Percent-encoding with URLEncoder keeps the value readable. URLEncoder turns spaces into +, which URLDecoder turns back. Base64url (- and _ instead of + and /, no = padding) works for any bytes, including the output of encryption or a MAC. Plain Base64.getEncoder() is also allowed in cookie values, but its +, / and = cause trouble when the value ends up in a URL.
HttpServer sends header values as they are. A value with CR or LF in it would let a client inject extra headers, which is one more reason never to put raw user input in a cookie.
Signed cookies
Cookies live on the client, so the client can change them. If a cookie stores anything the server trusts, such as a user ID, a role or an expiry, sign it with an HMAC. The server keeps the key, and a client can't produce a valid signature for a changed value:
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.Base64;
import java.util.Optional;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class SignedCookies {
static final Base64.Encoder B64 = Base64.getUrlEncoder().withoutPadding();
static final Base64.Decoder B64D = Base64.getUrlDecoder();
private final SecretKeySpec key;
SignedCookies(byte[] secret) {
this.key = new SecretKeySpec(secret, "HmacSHA256");
}
private byte[] mac(String data) {
try {
Mac mac = Mac.getInstance("HmacSHA256"); // Mac is not thread-safe: one per call
mac.init(key);
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
} catch (GeneralSecurityException e) {
throw new IllegalStateException(e);
}
}
// value = base64(payload) "." expiresEpochSeconds "." base64(hmac)
String sign(String name, String payload, Instant expires) {
String data = B64.encodeToString(payload.getBytes(StandardCharsets.UTF_8))
+ "." + expires.getEpochSecond();
// The cookie name is part of the signed data, so a value can't be moved to another cookie
return data + "." + B64.encodeToString(mac(name + "=" + data));
}
Optional<String> verify(String name, String value, Instant now) {
int lastDot = value.lastIndexOf('.');
if (lastDot < 0) return Optional.empty();
String data = value.substring(0, lastDot);
byte[] given;
try {
given = B64D.decode(value.substring(lastDot + 1));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
// Constant-time comparison; equals() would leak timing information
if (!MessageDigest.isEqual(given, mac(name + "=" + data))) return Optional.empty();
int dot = data.indexOf('.');
long expires = Long.parseLong(data.substring(dot + 1));
if (now.getEpochSecond() >= expires) return Optional.empty();
return Optional.of(new String(B64D.decode(data.substring(0, dot)), StandardCharsets.UTF_8));
}
public static void main(String[] args) {
// In production load a random 32+ byte key from configuration or a secret store
SignedCookies signer = new SignedCookies("change-me-to-32-random-bytes!!!!".getBytes(StandardCharsets.UTF_8));
Instant now = Instant.parse("2026-10-17T12:00:00Z");
String value = signer.sign("user", "id=42;role=user", now.plusSeconds(3600));
System.out.println("cookie: user=" + value);
System.out.println("valid: " + signer.verify("user", value, now));
// The attacker edits the payload to role=admin and keeps the old signature
String forgedPayload = B64.encodeToString("id=42;role=admin".getBytes(StandardCharsets.UTF_8));
String forged = forgedPayload + value.substring(value.indexOf('.'));
System.out.println("forged: " + signer.verify("user", forged, now));
System.out.println("renamed: " + signer.verify("admin", value, now));
System.out.println("expired: " + signer.verify("user", value, now.plusSeconds(7200)));
}
}
Output:
cookie: user=aWQ9NDI7cm9sZT11c2Vy.1792242000.cb_wYkqkQs4qZycYHCh3rf6YahLzyV67aQR8VCZHV_8
valid: Optional[id=42;role=user]
forged: Optional.empty
renamed: Optional.empty
expired: Optional.empty
Details that matter:
- Compare MACs with
MessageDigest.isEqual(). It takes the same time no matter where the first difference is.Arrays.equals()returns early, and an attacker can use the timing to guess a valid signature byte by byte. - Put the expiry inside the signed data.
Max-Ageonly tells an honest browser when to drop the cookie. A copied cookie can be replayed forever unless the server checks the time itself. - Include the cookie name in the MAC, so a value signed for one cookie can't be pasted into another.
- Signing doesn't hide anything: anyone can Base64-decode the payload. If the value must be secret, encrypt it with AES-GCM (which also authenticates it), or store the data on the server and keep only a random session ID in the cookie.
- A signed cookie can't be revoked before it expires. To log a user out everywhere, or to ban a user, you need server-side state. That's the main reason most apps use server-side sessions, where the cookie is just a random ID from
SecureRandom.
Parsing cookies in a filter
If several handlers need cookies, parse them once per request in a filter and store the result as an exchange attribute. Filters are explained in HTTP middleware:
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class CookieFilter {
static Map<String, String> parseCookies(List<String> headers) {
Map<String, String> cookies = new LinkedHashMap<>();
for (String header : headers) {
for (String pair : header.split(";")) {
int eq = pair.indexOf('=');
if (eq <= 0) continue;
String name = pair.substring(0, eq).trim();
if (!name.startsWith("$")) cookies.putIfAbsent(name, pair.substring(eq + 1).trim());
}
}
return Map.copyOf(cookies);
}
@SuppressWarnings("unchecked")
static Map<String, String> cookies(HttpExchange ex) {
return (Map<String, String>) ex.getAttribute("cookies");
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
HttpContext ctx = server.createContext("/", ex -> {
String lang = cookies(ex).getOrDefault("lang", "en");
byte[] body = (lang.equals("pl") ? "Cześć" : "Hello").getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
ex.sendResponseHeaders(200, body.length);
try (var out = ex.getResponseBody()) { out.write(body); }
});
// Parse once per request; handlers read the result from an attribute
ctx.getFilters().add(Filter.beforeHandler("parse cookies",
ex -> ex.setAttribute("cookies",
parseCookies(ex.getRequestHeaders().getOrDefault("Cookie", List.of())))));
server.start();
URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/");
HttpClient client = HttpClient.newHttpClient();
for (String cookie : new String[] {null, "lang=pl"}) {
var b = HttpRequest.newBuilder(uri);
if (cookie != null) b.header("Cookie", cookie);
var body = client.send(b.build(), HttpResponse.BodyHandlers.ofString()).body();
System.out.println(cookie + " -> " + body);
}
server.stop(0);
}
}
Output:
null -> Hello
lang=pl -> Cześć
The same filter is a good place to verify signed cookies and set the current user, so handlers never see an unverified value.
Cookies on the client: CookieManager
HttpClient doesn't keep cookies unless you give it a CookieHandler. The standard implementation is java.net.CookieManager, backed by an in-memory CookieStore. It stores cookies from Set-Cookie and adds a Cookie header to later requests, applying the domain, path, Secure and expiry rules:
import com.sun.net.httpserver.HttpServer;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ClientCookies {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/set", ex -> {
var h = ex.getResponseHeaders();
h.add("Set-Cookie", "plain=1; Path=/");
h.add("Set-Cookie", "admin=2; Path=/admin");
h.add("Set-Cookie", "secure=3; Path=/; Secure");
h.add("Set-Cookie", "tracker=4; Path=/; Domain=ads.example.com");
ex.sendResponseHeaders(204, -1);
ex.close();
});
server.createContext("/", ex -> {
System.out.printf(" %-12s Cookie: %s%n", ex.getRequestURI().getPath(),
ex.getRequestHeaders().getOrDefault("Cookie", java.util.List.of()));
ex.sendResponseHeaders(204, -1);
ex.close();
});
server.start();
String base = "http://localhost:" + server.getAddress().getPort();
// Default policy: ACCEPT_ORIGINAL_SERVER rejects cookies for other domains
CookieManager manager = new CookieManager();
HttpClient client = HttpClient.newBuilder().cookieHandler(manager).build();
// Add a cookie by hand, e.g. a session token obtained some other way
HttpCookie token = new HttpCookie("token", "t-123");
token.setPath("/");
token.setVersion(0);
manager.getCookieStore().add(URI.create(base), token);
for (String path : new String[] {"/set", "/", "/admin/users"}) {
client.send(HttpRequest.newBuilder(URI.create(base + path)).build(),
HttpResponse.BodyHandlers.discarding());
}
System.out.println("store:");
for (HttpCookie c : manager.getCookieStore().getCookies()) {
System.out.printf(" %s path=%s secure=%b%n", c, c.getPath(), c.getSecure());
}
server.stop(0);
}
}
Output:
/ Cookie: [token=t-123; plain=1]
/admin/users Cookie: [admin=2; token=t-123; plain=1]
store:
token=t-123 path=/ secure=false
plain=1 path=/ secure=false
admin=2 path=/admin secure=false
secure=3 path=/ secure=true
admin=2went only to/admin/users, and it came first because its path is more specific.secure=3was stored but not sent, because the requests used plainhttp://.tracker=4was rejected. The default policy,CookiePolicy.ACCEPT_ORIGINAL_SERVER, refuses cookies whoseDomaindoesn't match the server that sent them.CookieStore.add()lets you seed the store, for example with a token from a config file. Set the version to0: theHttpCookieconstructor creates a version 1 cookie, which would be sent in the RFC 2965 format shown earlier.
The built-in policies are ACCEPT_ORIGINAL_SERVER (the default), ACCEPT_ALL and ACCEPT_NONE. CookiePolicy is a functional interface, so a custom rule is a lambda. You can also call CookieManager directly, without a network, to check what it would store and send:
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.URI;
import java.util.List;
import java.util.Map;
public class CustomPolicy {
public static void main(String[] args) throws Exception {
// Accept only cookies from the original server, and never long-lived ones
CookiePolicy policy = (uri, cookie) ->
CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie)
&& (cookie.getMaxAge() == -1 || cookie.getMaxAge() <= 86_400);
CookieManager manager = new CookieManager(null, policy);
// put() is what HttpClient calls with each response's headers
URI uri = URI.create("https://api.example.com/v1/login");
manager.put(uri, Map.of("Set-Cookie", List.of(
"session=s1; Path=/; Secure; HttpOnly",
"prefs=p1; Path=/; Max-Age=3600; Expires=Fri, 01 Jan 2038 00:00:00 GMT",
"forever=f1; Path=/; Max-Age=315360000; Expires=Sat, 15 Oct 2036 12:00:00 GMT",
"other=o1; Path=/; Domain=evil.example.org")));
System.out.println("stored: " + manager.getCookieStore().getCookies());
// get() builds the Cookie header for an outgoing request
System.out.println("send: " + manager.get(URI.create("https://api.example.com/v1/me"), Map.of()));
System.out.println("http: " + manager.get(URI.create("http://api.example.com/v1/me"), Map.of()));
}
}
Output:
stored: [session=s1, prefs=p1]
send: {Cookie=[session=s1, prefs=p1]}
http: {Cookie=[prefs=p1]}
put() is what HttpClient calls with each response's headers, and get() returns the Cookie header for an outgoing request. session was left out of the http:// request because it's Secure.
A few more points about CookieManager:
- The store is in memory and lost when the program exits. To keep cookies between runs, implement
CookieStoreyourself (or copy the cookies out withgetCookies()and add them back on startup).HttpCookieisn'tSerializable, so save the fields you need. - One
CookieManageris one cookie jar. Share it betweenHttpClientinstances that should act as the same user, and use separate managers for separate users, for example in a load test. HttpURLConnectionuses the system-wide handler:CookieHandler.setDefault(new CookieManager()).HttpClientignores that default and uses only the handler passed tocookieHandler().CookieManagerignoresSameSiteand cookie prefixes. They protect against other sites in a browser, which doesn't apply to a program that talks to a few known servers.
Servlets and Spring
In Jakarta Servlet, cookies are objects of jakarta.servlet.http.Cookie. Since Servlet 6.0 there's setAttribute() for attributes that have no setter, such as SameSite:
import jakarta.servlet.http.Cookie;
public class ServletCookie {
public static void main(String[] args) {
Cookie session = new Cookie("session", "k3J9xQ2v");
session.setPath("/");
session.setHttpOnly(true);
session.setSecure(true);
session.setMaxAge(-1); // session cookie (the default)
session.setAttribute("SameSite", "Lax"); // Servlet 6.0+: any attribute
System.out.println(session.getName() + "=" + session.getValue()
+ " attributes=" + session.getAttributes());
// In a servlet: response.addCookie(session);
// Reading: Cookie[] cookies = request.getCookies(); // null when there are none
}
}
Output (compiled against jakarta.servlet-api 6.1.0):
session=k3J9xQ2v attributes={HttpOnly=, Path=/, SameSite=Lax, Secure=}
request.getCookies() returns null, not an empty array, when the request has no cookies, so check for it before looping.
Spring has ResponseCookie, a builder that produces the Set-Cookie string, including SameSite. It works the same in Spring MVC and WebFlux:
import java.time.Duration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
public class SpringCookie {
public static void main(String[] args) {
ResponseCookie session = ResponseCookie.from("session", "k3J9xQ2v")
.path("/")
.httpOnly(true)
.secure(true)
.sameSite("Lax")
.build();
ResponseCookie theme = ResponseCookie.from("theme", "dark")
.path("/")
.maxAge(Duration.ofDays(365))
.build();
ResponseCookie logout = ResponseCookie.from("session", "").path("/").maxAge(0).build();
System.out.println(HttpHeaders.SET_COOKIE + ": " + session);
System.out.println(HttpHeaders.SET_COOKIE + ": " + theme);
System.out.println(HttpHeaders.SET_COOKIE + ": " + logout);
}
}
Output (with spring-web 7.0.9):
Set-Cookie: session=k3J9xQ2v; Path=/; Secure; HttpOnly; SameSite=Lax
Set-Cookie: theme=dark; Path=/; Max-Age=31536000; Expires=Sun, 17 Oct 2027 20:19:00 GMT
Set-Cookie: session=; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT
In a controller return it with ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString()) and read cookies with a @CookieValue("theme") String theme parameter. Spring Boot can set the attributes of its own session cookie with properties such as server.servlet.session.cookie.same-site=lax.
Security checklist
- Session and auth cookies:
HttpOnly,Secure,SameSite=Lax(orStrict),Path=/, noDomain. The value should be a long random ID (at least 128 bits fromSecureRandom), not a user ID or anything guessable. - Cookie prefixes: a name starting with
__Host-(for example__Host-session) is accepted by browsers only withSecure,Path=/and noDomain. A subdomain or a plain-HTTP page then can't overwrite it.__Secure-only requiresSecure. Browsers enforce this;CookieManagerdoesn't. - Rotate the session ID on login. If you keep the ID the visitor had before logging in, an attacker who planted that ID (session fixation) is now logged in as the user.
- CSRF: the browser attaches cookies to requests that other sites trigger.
SameSite=Laxblocks cross-sitePOSTs in modern browsers. For anything sensitive add a CSRF token or check theOriginheader too. - Never trust cookie contents. Validate them like form input, and sign or encrypt anything the server relies on.
- Don't log
Cookieheaders. They contain credentials. Redact them in access logs and error reports.
Summary
- The server sends
Set-Cookie: name=value; attributes, one header per cookie. The client sends backCookie: a=1; b=2without the attributes. - On
HttpServeraddSet-CookiewithgetResponseHeaders().add()and parse theCookieheader yourself, skipping malformed pairs. Don't useHttpCookieon the server side. - Delete a cookie by setting it again with
Max-Age=0and the same name, path and domain. - Encode values with
URLEncoderor Base64url, and sign anything the server trusts with an HMAC compared usingMessageDigest.isEqual(). - On the client,
HttpClient.newBuilder().cookieHandler(new CookieManager())stores and sends cookies. SendExpiresalong withMax-Age, or the JDK switches to the old RFC 2965 format. - Servlets use
jakarta.servlet.http.Cookie(withsetAttribute("SameSite", ...)), Spring usesResponseCookie.