Codementor Events

How to use cookies in Spring Boot

Published Jul 25, 2019
How to use cookies in Spring Boot

An HTTP Cookie (also known as web cookie , 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 send 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.

Spring framework provides @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 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.

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 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";
}

If no expiration time is specified for a cookie, it lasts as long as the session is not expired. Such cookies as 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.

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 cookies are used to prevent cross-site scripting (XSS) attacks and are not accessible via JavaScript's Document.cookie API. When 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);

If 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 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);

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 of Cookie class and add it to the response.
  • To read all cookies, you can use HttpServletRequest's getCookies() method which returns an array of Cookie.
  • 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 and HttpOnly flags to avoid XSS attacks.
  • Set the Path=/ to make a cookie accessible everywhere for current domain.
  • To delete a cookie, set the Max-Age to 0 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.

Happy Coding 😍


🙋‍♂️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV.


This post was originally published on attacomsian.com/blog.

Discover and read more posts from Atta Shah
get started
post commentsBe the first to share your opinion
Show more replies