Spring Boot - Cookies

Lets learn how to use cookies for a Spring Boot application.

What is HTTP Cookies

An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user’s web browser. The browser may store it and send it back with later requests to the same server. Typically, it’s used to tell if two requests came from the same browser — keeping a user logged-in, for example. It remembers stateful information for the stateless HTTP protocol.

Session management Logins, shopping carts, game scores, or anything else the server should remember

Personalization User preferences, themes, and other settings

Tracking Recording and analyzing user behavior

The Set-Cookie HTTP response header from the server sets the cookie in the client side. Here is an example HTTP Response that sets a cookie with key foo. This cookie expires at 18-Jun-2020 02:39:49 GMT.

1
2
3
4
5
6
7
HTTP/1.1 200
Set-Cookie: foo=bar; Max-Age=604800; Expires=Thu, 18-Jun-2020 02:39:49 GMT
Content-Type: text/html;charset=UTF-8
Content-Length: 16
Date: Thu, 11 Jun 2020 02:39:49 GMT
Keep-Alive: timeout=60
Connection: keep-alive

The subsequent HTTP Request will have Cookie header set to include the Cookie value.

1
2
3
4
5
6
7
8
9
GET /readCookie HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;
Cookie: foo=bar

You can also use Javascript to set a cookie. Hre is an example to set a cookie named foo with value bar.

1
document.cookie = "foo=bar"

You can inspect a site’s cookie in the Application tab under storage/Cookies session.

Cookies Operations

You can create a cookie instance and add the cookie to the Http response. There are a few properties you can set for a Cookie.

The MaxAge attribute of the cookie sets the expiration of a cookie. default is -1. -1 means it is a Session Cookie. Session cookie will be erased when the user closes the browser.

A cookie with the Secure attribute is sent to the server only with an encrypted request over the HTTPS protocol. Set this attribute to be true to prevent man-in-the-middle attach.

A cookie with the HttpOnly attribute is inaccessible to the JavaScript Document.cookie API. Set this attribute to be true to prevent Cross-site scripting(XSS) attack.

The Domain attribute specifies which hosts are allowed to receive the cookie. If unspecified, it defaults to the same origin that set the cookie, excluding subdomains.

The Path attribute indicates a URL path that must exist in the requested URL in order to send the Cookie header.

1
2
3
4
5
6
7
8
9
10
// http://localhost:8080/setCookie
@GetMapping("/setCookie")
public String setCookie(HttpServletRequest request, HttpServletResponse response) {
Cookie cookie = new Cookie("foo", "bar");
cookie.setSecure(false);
cookie.setHttpOnly(false);
cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
response.addCookie(cookie);
return "cookie is added!";
}

You can use @CookieValue annotation to read a cookie’s value

1
2
3
4
5
// http://localhost:8080/readCookie
@GetMapping("/readCookie")
public String readCookie(@CookieValue("foo") String fooCookieValue) {
return "The value of foo cookie is " + fooCookieValue;
}

Another way to get Cookie value is via WebUtils. WebUtils has a getCookie method to get the first cookie with the given name, or null if none is found.

1
Cookie cookie = WebUtils.getCookie(request, "foo");

Get all Cookies

You can get all cookies from Http Request.

1
2
3
4
5
6
7
8
9
// http://localhost:8080/readAllCookie
@GetMapping("/readAllCookie")
public String readAllCookie(HttpServletRequest request, HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
if( cookies != null) {
return Stream.of(cookies).map(c-> c.getName() + "=" + c.getValue()).collect(Collectors.joining("<br>"));
}
return "No cookie is found!";
}

To delete a cookie, unset its value and set its MaxAge to be 0. Make sure the attributes also matches.

1
2
3
4
5
6
7
8
9
10
11
// http://localhost:8080/deleteCookie
@GetMapping("/deleteCookie")
public String deleteCookie(HttpServletRequest request, HttpServletResponse response) {
Cookie cookie = new Cookie("foo", null);
cookie.setMaxAge(0);
cookie.setSecure(false);
cookie.setHttpOnly(false);
response.addCookie(cookie);

return "cookie is deleted!";
}

Reference