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 | HTTP/1.1 200 |
The subsequent HTTP Request will have Cookie
header set to include the Cookie value.
1 | GET /readCookie HTTP/1.1 |
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
Set Cookie
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 | // http://localhost:8080/setCookie |
Get a Cookie
You can use @CookieValue
annotation to read a cookie’s value
1 | // http://localhost:8080/readCookie |
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 | // http://localhost:8080/readAllCookie |
Delete a Cookie
To delete a cookie, unset its value and set its MaxAge to be 0. Make sure the attributes also matches.
1 | // http://localhost:8080/deleteCookie |
Reference