primers

Cookie 🍪 ~

Is the front end of the actual work will encounter (ah? Why say yes…)

And since a recent Chrome update changed the default value of the Cookie sameSite property, some projects will be affected to varying degrees

Therefore, I took the opportunity to sort out cookie related things and show the process and results of the experiment

Show the process and results of the experiment, and welcome to point out any inaccuracies or unscientific places

disclaimer

The author is not fine and lazy to die, if there are mistakes in this article are not responsible for welcome to point out the fate of correction

Welcome to gitGithub.com/YuArtian/bl…

About the cookie

Cookies are different from other storage methods. Although they are stored on the client side, they are set by the server. It is also used to communicate with servers

Cookies are mainly used for the following three aspects:

  • Session state management (such as user login status, shopping cart, game score, or other information that needs to be logged)
  • Personalization (such as user-defined Settings, themes, etc.)
  • Browser behavior tracking (e.g. tracking and analyzing user behavior, etc.)

Create cookie:

  • Set by the server and set in the responseSet-CookieIn response to the head
  • Set by the client and useddocument.cookieTo read and write

After the request is successfully created, the Cookie field is used to send the Cookie of the corresponding domain name to the server

Cookies are stored in key=value format. You can set additional attributes, declare the scope and validity time of a cookie, etc. These Settings are written in the set-cookie field as follows:

Set-Cookie: key=value; Path=/; Domain=xx.com; Max-Age=10086;

More details —-> from MDN

The same-origin policy and cookie

For security purposes, the browser adopts the same-origin policy. Cookies must meet the same-origin requirement

That is, the current page and the response with the set-cookie header must satisfy same-origin (the protocol, address, and port number must be the same).

Let’s start by experimenting with different source failures

Failure case

For comprehensive coverage, we experiment with IP address and domain name respectively

So anyway, we’re going to make an index.html request, and app.js is going to be the server that accepts the request, trying to plant a cookie, right

The code is as follows:

index.html

app.js

Using an IP address

Next, we can’t just click on index.html. So file://… Anyway, we need a service here

I’m using HTTP-Server for simplicity (mostly on my computer). Enter the http-server command at the index. HTML directory terminal

Open up 127.0.0.1:8080 to see our page, but you’ll notice that despite the set-cookie field in the response, the Cookie was not planted successfully

It failed because on the browser our address was 127.0.0.1:8080, yet the response with the set-cookie header came from 127.0.0.1:3000. The ports are different, so they’re not homologous, so the cookie doesn’t grow

Using the domain name

To afford a domain name… We can change the local host configuration to

# cookie 127.0.0.1 at a.comCopy the code

The http-server startup command is changed to

http-server -p 80
Copy the code

To access our index.html, type “a.com” in the address bar, and of course change the request

fetch('http://a.com:3000/givemeacookie').then(...)
Copy the code

Of course, the results were the same

Same-origin cookie Settings

It is definitely not possible to have different sources of cookies. …).

Anyway, let’s look at the successful cases of homology

Server side rendering

The previous examples were all cases where the front and back ends were separated, so you have to have different sources. If it is a page directly from the server

Here we just need to change app.js

This time go directly to a.com:3000

It’s finally planted.

However, while it is convenient to use the server, you won’t have to change the project completely just for cookies

Nginx proxy

To achieve the purpose of the same source, but also want to separate the front and back end, we can use the proxy gateway to help us forward, the browser deceive the past…

Start by installing nginx

Homebrew installation is recommended for Mac. It is too annoying to decompress and compile by yourself

Direct Brew Search Nginx is simple and effortless

This may occur when ngniX is started

nginx: [error] open() "/usr/local/var/run/nginx.pid" failed (2: No such file or directory)

/usr/local/etc/nginx = /usr/local/etc/nginx Then run nginx – c/usr/local/etc/nginx/nginx. Conf run nginx – s reload again, is ok

Find the nginx.conf configuration file location and rewrite the Ngnix configuration as shown below:

With nginx we don’t have to use http-server to access 127.0.0.1:8888

Of course, remember to change the request address in index.html as well

fetch('/api/givemeacookie').then(...)
Copy the code

In this way, it becomes homogenous through Nginx. Remember to set the path of the cookie

res.setHeader('set-cookie'['cookie=aCookieFromServer; Path=/']);
Copy the code

Otherwise, you can’t get the corresponding cookie in the front end

You can see that the cookie has been set successfully. It can be read in the front end, and the Cookie request header will be carried in the subsequent request, and the content of the Cookie can also be accepted by the back end

Sending and receiving of cross-domain cookies

Must cookies not be used across domains?

Using CORS (Cross-domain resource sharing) allows you to break through the same-origin constraint to use cookies

But this requires the cooperation of both the server and client sides

First, when the client sends the request:

If XMLHttpRequest is used, you need to configure xhr.withCredentials = true;

To use fetch, you need to configure the credentials: ‘include’

The specific code is shown below:

Accordingly, the server adds a response header

Access-Control-Allow-Credentials: true
Copy the code

Access-control-allow-origin does not use the wildcard *, but only a single domain name.

Change the code as follows :(since CORS is used, nginx is not needed here.)

Http-server -p 80 = 127.0.0.1

In addition, because access-Control-Allow-Origin only allows a single domain name, in actual use the server needs to maintain an Origin list. Verify that the Origin field in the request header is valid. After verification, you can directly set it to the access-Control-Allow-Origin value.

Access-control-allow-origin can be set dynamically for multiple domains

At the end

So far, we’ve tried cookies in various postures. Cookies can always be used across domains or not

Later it may be more extended to experiment with other applications of cookies

Say hey.