foreword

Recently, I used next.js to develop a front-end website. I found that there are problems with cookie storage and cross-domain during the login process. I have never understood the principle of cookies. After reading the articles of many big guys on the Internet, I have learned a lot to share with you.

Introduction to Cookies

An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser. The browser may store the cookie and send it back to the same server with subsequent requests. Typically, HTTP cookies are used to tell if two requests are from the same browser - for example, to keep the user logged in. It remembers stateful information for the stateless HTTP protocol.

Cookies are mainly used for three purposes:

1. Session management: such as logins, shopping carts, game scores, or anything else the server should remember
2. Personalization: such as user preferences, themes and other settings
3. Tracking: such as recording and analyzing user behavior

1. Create cookies
After receiving an HTTP request, the server MAY send one or more Set-Cookie response headers. Browsers typically store cookies and send them with requests to the same server within the Cookie HTTP header. You can specify an expiration date or time period when cookies should not be sent. You can also set additional restrictions on specific domains and paths to limit where cookies are sent.

Set-Cookie and Header Cookies

HTTP response (Response) header (Header) Set-Cookie role: send cookies from the server to the user agent.
A simple cookie setting is as follows:

 Set-Cookie: <cookie-name>=<cookie-value>

This instructs the server to send a header telling the client to store a pair of cookies:

 HTTP/2.0 200 OK
Content-Type: text/html
Set-Cookie: yummy_cookie=choco
Set-Cookie: tasty_cookie=strawberry

Then, for each subsequent request to the server, the browser will use the header to bring back any previously stored cookies to the server cookies.

 GET /sample_page.html HTTP/2.0
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry

2. The life cycle of cookies

The lifetime of a cookie can be defined in two ways:

1. When the current session ends: the session cookie will be deleted. (The browser defines when the "current session" ends, some browsers use session recovery on restart. This may cause session cookies to persist indefinitely)
2. Permanent cookie: Max-Age is deleted after the date specified by the Expires attribute or after a period of time specified by the attribute.

E.g:

 Set-Cookie: id=a3fWa; Expires=Thu, 31 Oct 2021 07:28:00 GMT;

Notice:
1. When you set the Expires date and time, they relate to the client that set the cookie, not the server.
2. To delete a cookie, you need to set Max-Age to 0, and set the value of the cookie to null. Do not set the Max-Age directive value to a negative number of -1. Otherwise, the browser treats it as a session cookie.
3. If your site authenticates the user, it should regenerate and resend the session cookie, even if it already exists, as long as the user is authenticated. This approach helps prevent session fixation attacks, where third parties can reuse a user's session.

3. Restrict access to cookies

You can ensure that cookies are sent securely and cannot be accessed by unintended parties or scripts in one of two ways:
1. Secure attribute
2. HttpOnly attribute.

Cookies with this Secure attribute are only sent to the server with encrypted requests over the HTTPS protocol. It is never sent using insecure HTTP (except localhost), which means it cannot be easily accessed by a man-in-the-middle attacker. Insecure sites (with http: in the URL) cannot use the Secure attribute to set cookies. However, don't assume that this will Secure block all access to sensitive information in the cookie. For example, someone with access to the client's hard drive (or JavaScript, if HttpOnly doesn't set that property) can read and modify the information.

JavaScript API HttpOnly: cannot access cookie with this attribute;
Document.cookie it is only sent to the server.
For example, cookies that persist across server-side sessions do not need to be available to JavaScript and should have the HttpOnly attribute. This precaution helps mitigate cross-site scripting (XSS) attacks.

Here is an example:

 Set-Cookie: id=a3fWa; Expires=Thu, 21 Oct 2021 07:28:00 GMT; Secure; HttpOnly

4. Define the sending location of the cookie

The Domain and Path properties define the scope of the cookie: which URLs the cookie should be sent to.

4.1 Domain property

The Domain attribute specifies which hosts can receive cookies. If not specified, the attribute defaults to the same host that set the cookie, excluding subdomains.
If Domain is specified, subdomains are always included. Therefore, specifying Domain is less restrictive than omitting it. However, it can be helpful when subdomains need to share information about users.

For example, if you set Domain=mozilla.org, cookies are available for subdomains such as developer.mozilla.org.

4.2 Path property

The Path property indicates the URL path that must exist in the requested URL in order for the Cookie header to be sent. ( %x2F"/") characters are treated as directory separators, and subdirectories are also matched.
For example, if you set Path=/docs, these request paths match:

 /docs
/docs/
/docs/Web/
/docs/Web/HTTP

But these request paths do not:

 /
/docsets
/fr/docs

4.3 SameSite attribute

The SameSite attribute allows the server to specify when to send cookies with cross-site requests (where the site is defined by a registrable domain and scheme: http or https). This provides some protection against cross-site request forgery attacks (CSRF). It takes three possible values: Strict, Lax and None.

When using Strict, the cookie is only sent to its originating site.
Lax is similar, except the cookie is sent when the user navigates to the cookie's origin site. For example, by following links from external sites.
None specifies that the cookie is sent both when making a request and when making a cross-site request, but only in a security context (that is, if the SameSite=None attribute must also be set).

Note: If the SameSite attribute is not set, the cookie is treated as Lax by default.

Example: For example: website a.com has cookie:name=Justin,samesite=xxx, website b.com has no cookie

  • 1. When xxx=strict and b.com accesses the interface of a.com, neither get nor post requests will bring the cookie of a.com to the interface of a
  • 2. When xxx=lax and b.com accesses the interface of a.com, get will bring the cookie of a.com to the interface of a, and post will not
  • 3. When xxx=none and b.com accesses the interface of a.com, both get and post requests will bring the cookie of a.com to the interface of a

     Set-Cookie: mykey=myvalue; SameSite=Strict|Lax|None

Note: If b.com is a subdomain of a.com, such as: b.com=api.a.com, no matter what the samesite is equal to, the cookies of a.com will be taken over there

question

After introducing cookies, let's assume that we now have a project with front-end and back-end separation. The front-end address is: www.baidu.com, and the back-end api addresses are: api.baidu.com and api.bilibili.com. Now let's analyze the following a few questions:

1. Cross-domain front-end and back-end settings
2. The problem that cross-domain cookies cannot be carried
3. How can cookies avoid XSS attacks and CSRF attacks?

1. Cross-domain front-end and back-end settings

If you want the front end to access the two api addresses in the background, we need to set the following code,

Front end (take axios as an example):

 axios.defaults.withCredentials = true

Background (take spring cloud gateway as an example)

 spring:
  cloud:
    loadbalancer.ribbon.enabled: false
    gateway:
      globalcors:
        #add-to-simple-url-handler-mapping: true
        cors-configurations:
          '[/**]':
            allowedHeaders: "*"
            allowCredentials: true
            allowedOrigins: 
              - "https://api.baidu.com"
              - "https://api.bilibili.com"
            allowedMethods: "*"
      default-filters:
        - DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials

2. The problem that cross-domain cookies cannot be carried

This is interesting, because our front-end address is www.baidu.com, referred to as A, and the background api has two addresses: api.baidu.com, referred to as B and api.bilibili.com, referred to as C, when we request through A When the interface of B is used, the cookie will be automatically carried, because they belong to the same origin and different domains, so the cookie you set under A will also be carried when requesting B, but not when A requests C, obviously Two different origins are also in different domains, so they can't be brought. If you really want to bring it, only when A requests C, it will bring C's cookie to C, but not A's cookie to C, so now you know what to do Do it!

3. How cookies avoid XSS attacks and CSRF attacks

Introduction to XSS:
(Cross Site Script) attack is called cross-site scripting attack. Xss attack usually refers to the use of loopholes left by web page development to inject malicious instruction code into web pages through clever methods, so that users can load and execute maliciously created web page programs. . These malicious web programs are usually JavaScript code

XSS solution:
Strictly speaking, HttpOnly is not to fight against XSS - HttpOnly solves the cookie hijacking attack after XSS. As mentioned earlier, XSS may steal the user's cookie, and then directly log in to the user's account, but if the cookie is set to HttpOnly, this attack will fail because JavaScript cannot read the value of the cookie.

CSRF introduction:
The full name of CSRF attack is cross site request forgery, which is a malicious use of websites. Simply put, a malicious website (attacker) steals your identity and sends malicious requests to trusted websites in your name. The things that CRSF can do include using your identity to send emails, text messages, transaction transfers, etc., and even steal your account.

Three necessary conditions for a CSRF attack:
The target site must have a CSRF vulnerability. The user has to log in to the target site and maintain the login state of the site on the browser. The user needs to open a third-party site, which can be a hacker's site or some forums.

CSRF attacks do not inject malicious scripts into pages, but find vulnerabilities in the server. Therefore, hackers cannot obtain user page data through CSRF attacks. For CSRF attacks, the main protection method is to improve the security of the server.

CSRF solution:
If the request is initiated from a third-party site, the browser needs to prohibit sending certain key cookie data to the server;
If the request is initiated by the same site, it is necessary to ensure that the cookie data is sent normally.
The SameSite attribute in Cookie is to solve this problem.

In the HTTP response header, the SameSite option can be included when setting a cookie through the set-cookie field.

Summarize

1. Cookie is a knowledge point that all front-end developers must face. Everyone must understand the principle, so that if you encounter cross-domain or xss, csrf attack prevention in actual development, you can have a targeted

quote

Using HTTP cookies
Browser Principles 33 # CSRF Attack: Why is there a SameSite attribute in cookies?
【Information Security】Interview frequently asked CSRF, cookie, session and token
The browser cross-domain request was successful, but the cookie was not carried over. Solve?


Awbeci
3.1k 声望213 粉丝

Awbeci


引用和评论

0 条评论