How to Use Cookies in Spring Boot
Check out this post to learn more about using web cookies in Spring Boot.
Join the DZone community and get the full member experience.
Join For FreeAn HTTP Cookie (also known as a web cookie or browser cookie) is a small piece of information stored by the server in the user's browser. The server sets the cookies while returning the response for a request made by the browser. The browser stores the cookies and sends them back with the next request to the same server. Cookies are generally used for session management, user-tracking, and to store user preferences.
Cookies help server remember the client across multiple requests. Without cookies, the server would treat every request as a new client.
In this tutorial, we will learn how to read, set, and remove HTTP cookies in a Spring Boot application.
Reading HTTP Cookie
The Spring Framework provides the @CookieValue
annotation to get the value of any HTTP cookie without iterating over all the cookies fetched from the request. This annotation can be used to map the value of a cookie to the controller method parameter.
@GetMapping("/")
public String readCookie(@CookieValue(value = "username", defaultValue = "Atta") String username) {
return "Hey! My username is " + username;
}
In the above code snippet, notice the defaultValue = "Atta"
. If the default value is not set, Spring will throw a java.lang.IllegalStateException
exception on failure to find the cookie with name username
in HTTP request.
Setting HTTP Cookie
To set a cookie in Spring Boot, we can use HttpServletResponse
class's method addCookie()
. All you need to do is to create a new instance of Cookie
class and add it to the response.
@GetMapping("/change-username")
public String setCookie(HttpServletResponse response) {
// create a cookie
Cookie cookie = new Cookie("username", "Jovan");
//add cookie to response
response.addCookie(cookie);
return "Username is changed!";
}
Reading All Cookies
Instead of using @CookieValue
annotation, we can also use HttpServletRequest
class as a controller method parameter to read all cookies. This class provides getCookies()
method, which returns all cookies sent by the browser as an array of Cookie
.
@GetMapping("/all-cookies")
public String readAllCookies(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
return Arrays.stream(cookies)
.map(c -> c.getName() + "=" + c.getValue()).collect(Collectors.joining(", "));
}
return "No cookies";
}
Cookie Expiration
If no expiration time is specified for a cookie, it lasts as long as the session is not expired. Such cookies are called session cookies. Session cookies remain active until the user closes their browser or clears their cookies. The username
cookie created above is in fact a session cookie.
But you can override this default behavior and set the cookie expiration time using setMaxAge()
method of Cookie
class.
// create a cookie
Cookie cookie = new Cookie("username", "Jovan");
cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
//add cookie to response
response.addCookie(cookie);
Now, instead of expiring when the browser is closed, the username
cookie will remain active for the next 7 days. Such cookies, which expire at a specified date and time, are called permanent cookies.
The expiry time passed to
setMaxAge()
method is in seconds. The expiry date and time is relative to the client where the cookie is being set, not the server.
Secure Cookie
A secure cookie is the one which is only sent to the server over an encrypted HTTPS connection. Secure cookies cannot be transmitted to the server over unencrypted HTTP connections.
// create a cookie
Cookie cookie = new Cookie("username", "Jovan");
cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
cookie.setSecure(true);
//add cookie to response
response.addCookie(cookie);
HttpOnly Cookie
HttpOnly cookies are used to prevent cross-site scripting (XSS) attacks and are not accessible via JavaScript's Document.cookie
API. When the HttpOnly
flag is set for a cookie, it tells the browser that this particular cookie should only be accessed by the server.
// create a cookie
Cookie cookie = new Cookie("username", "Jovan");
cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
cookie.setSecure(true);
cookie.setHttpOnly(true);
//add cookie to response
response.addCookie(cookie);
Cookie Scope
If the scope is not specified, a cookie is only sent to the server for a path that was used to set it in the browser. We can change this behavior using setPath()
method of the Cookie
class. This sets the Path
directive for the cookie.
// create a cookie
Cookie cookie = new Cookie("username", "Jovan");
cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
cookie.setSecure(true);
cookie.setHttpOnly(true);
cookie.setPath("/"); // global cookie accessible every where
//add cookie to response
response.addCookie(cookie);
Deleting Cookie
To delete a cookie, set the Max-Age
directive to 0
and unset its value. You must also pass the same other cookie properties you used to set it. Don't set the Max-Age
directive value to -1
. Otherwise, it will be treated as a session cookie by the browser.
// create a cookie
Cookie cookie = new Cookie("username", null);
cookie.setMaxAge(0);
cookie.setSecure(true);
cookie.setHttpOnly(true);
cookie.setPath("/");
//add cookie to response
response.addCookie(cookie);
Source code: Download the complete source code from GitHub available under MIT license.
Summary
Cookies provide a way to exchange the information between the server and the browser to manage sessions (logins, shopping carts, game scores), remember user preferences (themes, privacy policy acceptance), and to track the user behavior across the site.
Spring Boot provides an easy way to read, write, and remove HTTP cookies.
@CookieValue
annotation maps the value of the cookie to the method parameter. You should set the default value to avoid runtime exception when the cookie is not available.HttpServletResponse
class can be used to set a new cookie in the browser. You just need to create an instance ofCookie
class and add it to the response.- To read all cookies, you can use
HttpServletRequest
'sgetCookies()
method which returns an array ofCookie
. Max-Age
directive specifies the date and time when the cookie should expire.- If you are storing sensitive information in a cookie, make sure to set
Secure
andHttpOnly
flags to avoid XSS attacks. - Set the
Path=/
to make a cookie accessible everywhere for the current domain. - To delete a cookie, set the
Max-Age
to0
and pass all the properties you used to set it.
That's all, folks, for using cookies in a Spring Boot application. If you have any question or feedback, please feel free to send me a tweet anytime.
This article was originally published on attacomsian.com/blog.
Published at DZone with permission of Atta Shah. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments