A, takeaway

This article outline

  • Read the HTTP cookies
  • Set the HTTP cookies
  • Read all cookies []
  • Set the expiration time for cookies
  • Https and cookies
  • HttpOnly Cookie
  • Delete the Cookie

HTTP cookies (also known as Web cookies, browser cookies) are small pieces of data that the server stores in the user’s browser. The cookie is set by the server-side application when it returns the browser request response, and the browser stores the cookies and automatically returns them to the server-side application when the next request is sent together.

Cookies provide a way to exchange information between the server and the browser to manage sessions (login, shopping cart, game score), remember user preferences (themes, privacy policy acceptance), and track user behavior throughout the site. Cookies relieve some of the pressure on the server side, because some of the data is stored in the browser side, so this part of the data cannot be related to application security. In this article, you’ll learn how to read, set, and delete HTTP cookies in a Spring Boot application.

2. Read HTTP cookies

The Spring framework provides the @Cookievalue annotation to retrieve the value of the HTTP cookie, which can be used directly in controller method parameters.



@GetMapping("/")
public String readCookie(@CookieValue(value = "username", 
                                      defaultValue = "Atta") String username) {
    return "Hey! My username is " + username;
}
Copy the code

In the code snippet above, notice defaultValue = “Atta”. If not set a default value, and didn’t find the name for the username of cookies, Spring will be thrown. Java lang. An IllegalStateException anomalies.

3. Set HTTP cookies

To set cookies in Spring Boot, we can use the method addCookie() of the HttpServletResponse class. All you need to do is create a new Cookie object and add it to the response.

@getMapping ("/change-username") public String setCookie(HttpServletResponse Response) {// Create a cookie object  new Cookie("username", "Jovan"); Response.addcookie (cookie); return "Username is changed!" ; }Copy the code

4. Read all cookies []

In addition to using the @Cookievalue annotation, we can also use the HttpServletRequest class as a controller method parameter to read all cookies. This class provides the getCookies() method, which returns all cookies sent by the browser as an array.

@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"; }Copy the code

Set the expiration time for cookies

If no expiration time is specified for a cookie, its life lasts until the Session expires. Such cookies are called session cookies. Session cookies remain active until the user closes their browser or clears their cookies. But you can override this default behavior and set the expiration time of cookies using the class’s setMaxAge() method.

Cookie cookie = new cookie ("username", "Jovan"); cookie.setMaxAge(7 * 24 * 60 * 60); Response.addcookie (cookie); response.addcookie (cookie);Copy the code

The usernameCookie will now not expire at the end of the Seesion, but will remain valid for the next 7 days. The expiration time passed to the setMaxAge() method is in seconds. The expiration date and time are relative to the client setting the cookie, not the server.

Https and Cookies

We need to understand a concept: what secure Cookies? Secure cookies are cookies that can only be sent to the server over an encrypted HTTPS connection. Cookies cannot be sent to the server over an unencrypted HTTP connection. That is, if setSecure(true) is set, the Cookie cannot be transmitted over Http connections, only over Https connections.

Cookie cookie = new cookie ("username", "Jovan"); cookie.setSecure(true); //Https secure cookie // addCookie object to response response. AddCookie (cookie);Copy the code

Seven, HttpOnly cookies

HttpOnly cookies are used to protect against cross-site scripting (XSS) attacks, that is, HttpOnly cookies cannot be accessed through JavaScript’s Document.cookieAPI, Only by server programs on the server side.

Cookie cookie = new cookie ("username", "Jovan"); cookie.setHttpOnly(true); Response.addcookie (Cookie); response.addcookie (Cookie);Copy the code

Delete cookies

To delete cookies, you need to set max-age to 0 and the value of cookies to null. Do not set the max-age directive to a negative value of -1. Otherwise, the browser treats it as a session cookie.

// Set the value of Cookie to null Cookie Cookie = new Cookie("username", null); // set 'max-age' to 0 cookie.setMaxAge(0); response.addCookie(cookie);Copy the code

We look forward to your attention

  • The blogger has recently written a new book: “SpringBoot Series – Chapter 16, Verse 97.”
  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.