A web cookie is a small piece of data stored by the server in the user's browser to track user behavior, facilitate session management, and more. The cookie is sent to the client browser while returning the response for an HTTP request.

Here is an example that shows how to set a cookie while sending back ResponseEntity as a response for a RESTful web service:

@GetMapping("/login")
@ResponseBody
public ResponseEntity<?> login(@RequestBody String credentials, HttpServletResponse response) {

    // create a cookie
    Cookie cookie = new Cookie("platform","mobile");

    // expires in 7 days
    cookie.setMaxAge(7 * 24 * 60 * 60);

    // optional properties
    cookie.setSecure(true);
    cookie.setHttpOnly(true);
    cookie.setPath("/");

    // add cookie to response
    response.addCookie(cookie);

    // TODO: add your login logic here
    String jwtToken = "NOT_AVAILABLE";

    // return response entity
    return new ResponseEntity<>(jwtToken, HttpStatus.OK);
}

The above code uses HttpServletResponse to add a cookie to the response. Here are what the response headers look like:

HTTP/1.1 200
Set-Cookie: platform=mobile; Max-Age=604800; Expires=Sat, 10-Aug-2019 12:14:41 GMT; Path=/; Secure; HttpOnly
Content-Type: text/html;charset=UTF-8
Content-Length: 13
Date: Sat, 03 Aug 2019 12:14:41 GMT

Another way is to add the cookie as a raw Set-Cookie header while building the ResponseEntity object:

HttpHeaders headers = new HttpHeaders();
headers.add("Set-Cookie","platform=mobile; Max-Age=604800; Path=/; Secure; HttpOnly");
ResponseEntity.status(HttpStatus.OK).headers(headers).build();

Read how to use cookies in Spring Boot guide to find out more options for reading and writing cookies in Spring Boot.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.