What is a Cookie?

1, What is a Cookie?

HTTP Cookie (also known as Web Cookie or browser Cookie) is a small piece of data sent by the server to the user's browser and saved locally. It will be carried and sent to the server the next time the browser sends a request to the same server. Usage scenario:

  • Session state management (such as user login status, shopping cart, game score or other information to be recorded)
  • Personalized settings (such as user-defined settings, themes, etc.)
  • Browser behavior tracking (such as tracking and analyzing user behavior)
2, Cookie generation process
1. Generate cookie s

The server generates Cookie data and sets it to the set Cookie property, which is included in the Header of the HTTP protocol to tell the browser to save these data (unless the browser disables cookies).

// Data sent by the server to the browser
HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: yummy_cookie=choco
Set-Cookie: tasty_cookie=strawberry
2. Store cookie s and send them back

In the next request, the browser will set the stored cookie data as the cookie attribute, include it in the Header of the HTTP protocol, and send it to the server together with the request (unless it is set not to send cookies).

// Data sent by browser to server
GET /sample_page.html HTTP/1.1
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry
3, First party and third party cookies
  • The domain name in the cookie is the same as the domain name of the current site, which is called the first party cookie;
  • The domain name in the cookie is different from the domain name of the current site, which is called a third-party cookie;

The current site will use some other site resources (such as pictures and advertisements). When requesting a third-party server to obtain these resources, it will also return the set cookie attribute to let the browser retain the third-party cookies. These cookies are mainly used for user tracking, traffic analysis, etc.

4, Important properties of cookie s
1. Secure and HttpOnly

Function: restrict the way to access cookies.

  • Secure: indicates that cookie s can only be sent to the requesting site by https encryption;
  • HttpOnly: the JavaScript API cannot access the cookie with HttpOnly attribute (Document.cookie cannot read the cookie). This attribute can be set when the data in the cookie is only used for the server; It can prevent accessing cookie values through JavaScript;
  • These two attributes can effectively defend against most XSS attacks.
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly
2. Domain and Path

Function: which URL s are cookies allowed to be sent to?

  • Domain: indicates the domain name to which the cookie can be sent, including its subdomain name. If domain is not set, the value is the child domain name of origin but does not contain origin. If Domain=mozilla.org is set, the cookie can also be sent to the sub domain developer.mozilla.org.
  • Path: indicates which paths the cookie can be sent to. If Path=/docs is set, the cookie can also be sent to the sub path / docs/Web /.
3,SameSite

Function: it can limit the cross domain sending of cookie s. This attribute can effectively prevent most CSRF attacks. There are three values that can be set:

  • None: cookie s are sent for both intra site and cross site requests, but they need to be used together with the Secure attribute.
Set-Cookie: flavor=choco; SameSite=None; Secure
  • Strict: Send a cookie when the current page and the jump page are the same site;
Set-Cookie: key=value; SameSite=Strict
  • Lax: similar to Strict, except when users navigate to a URL from an external site (for example, through a link). In the new version of the browser, as the default option, the same site cookies will be reserved for some cross site sub requests, such as image loading or frames calling, but will be sent only when the user navigates to the URL from the external site. Such as link link
4,__ Host - and__ Secure-

There are many places where cookies can be created. It is difficult to determine the source of cookies, but the cookie prefix can be used to assert the source of cookies.

  • __Host-

Cookies with this prefix must have these three characteristics: Secure attribute, no Domain attribute, and Path value of /. Such cookie s are called Domain locked.

  • __Secure-

A cookie with this prefix indicates that it must have a Secure attribute.

Since the application server only checks the specific cookie name when determining whether the user has passed authentication or the CSRF token is correct, this effectively acts as a defense against session hijacking.

5, Methods of operating cookies
1,JavaScript API

The Document.cookie is used to create cookies in JavaScript code, and it can also be used to access cookies without HttpOnly flag.

document.cookie = "yummy_cookie=choco";
document.cookie = "tasty_cookie=strawberry";
console.log(document.cookie);
// logs "yummy_cookie=choco; tasty_cookie=strawberry"
2. cookie Library

The Node.js project is a Web service created with http. You can operate cookies with the cookie library. Examples are as follows:

var cookie = require('cookie');
var escapeHtml = require('escape-html');
var http = require('http');
var url = require('url');

function onRequest(req, res) {
  // Parse the query string
  var query = url.parse(req.url, true, true).query;

  if (query && query.name) {
    // Set a new cookie with the name
    res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), {
      httpOnly: true,
      maxAge: 60 * 60 * 24 * 7 // 1 week
    }));

    // Redirect back after setting cookie
    res.statusCode = 302;
    res.setHeader('Location', req.headers.referer || '/');
    res.end();
    return;
  }

  // Parse the cookies on the request
  var cookies = cookie.parse(req.headers.cookie || '');

  // Get the visitor name set in the cookie
  var name = cookies.name;

  res.setHeader('Content-Type', 'text/html; charset=UTF-8');

  if (name) {
    res.write('<p>Welcome back, <b>' + escapeHtml(name) + '</b>!</p>');
  } else {
    res.write('<p>Hello, new visitor!</p>');
  }

  res.write('<form method="GET">');
  res.write('<input placeholder="enter your name" name="name"> <input type="submit" value="Set Name">');
  res.end('</form>');
}

http.createServer(onRequest).listen(3000);
3. Cookie parser Library

cookie parser is used in express project to operate cookies. Examples are as follows:

var express = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

app.get('/', function (req, res) {
  // Cookies that have not been signed
  console.log('Cookies: ', req.cookies)

  // Cookies that have been signed
  console.log('Signed Cookies: ', req.signedCookies)
})

app.listen(8080)

// curl command that sends an HTTP request with two cookies
// curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello"
6, Massive data storage problems

A large amount of server data is stored in cookies, which reduces the network access performance (especially in mobile environment). It can be solved through Web Storage API and IndexedDB.

7, Reference documents

Posted on Thu, 25 Nov 2021 15:42:29 -0500 by ruzztec