Cookies share many features with
Cookies are stored on a user's computer and can be cleared by the user.
But unlike the modern API's, cookies have some built-in security features that make them useful for handling authentication.
Cookies can be used for authentication purposes, both in stateless and stateful methods.
Cookies can safely store a session id in the browser. The server stores the actual session.
Cookies can store tokens securely in single-page applications.
Cookies can be set by servers using HTTP headers.
To set a cookie in the user's browser, a request must include a
Multiple cookies can be set in the same request using separate headers.
The browser automatically sends cookies to the server using the
Cookie: session_id=abc123; tracking_id=987qwe;
Cookies can be permanent or limited to the user's current session.
Session cookies are deleted whenever the user's session ends. Each browser determines when a session is over, but it's usually when the browser is closed.
Permanent cookies are stored in the browser until it's deleted by the user or until it expires. An expiration date can be set using the
Set-Cookie: <key>=<value>; Expires=<date>;
Cookies contain meta-information in the form of attributes.
Secure attribute ensures that a cookie can only be set or returned on an HTTPS connection. This attribute is a good security measure against man-in-the-middle attacks because the cookie contents are encrypted.
Domain attribute specifies which host can receive the cookie.
The browser will send the cookie to the domain stored in this attribute, including subdomains. If a cookie does not have this attribute, the browser will only send the cookie to the domain it was set from, excluding subdomains.
Path attribute is similar to the
Domain attribute, except it can specify a specific path that must be present in the URL before the browser includes the cookie with the request.
SameSite attribute specifies where a cookie can come from. The value
Strict means it's only allowed to come from the same URL that stored the cookie. The value
Lax is similar to
Strict, except it will also be permitted when navigating to a page from an external URL. The value
None means there aren't any restrictions.
SameSite attribute to
Lax can help mitigate CSRF attacks.
The difference between
SameSite attributes is that
Domain specifies where the browser will send cookies, whereas
SameSite determines where the cookie may come from.