This article is a practical understanding of the previous article (Cookie Theory Knowledge)

Complete code:

The complete code

Cookie function during login registration:

registered

When registering, write the account and password into the database

The login

The server sends a Cookie to the browser on the first login.

Background login routing code (nodejs):

else if (path === '/sign_in' && method === 'POST') { readBody(request).then((body) => { let strings = body.split('&') //  ['email=1', 'password=2', 'password_confirmation=3'] let hash = {} strings.forEach((string) => { // string == 'email=1' let parts = string.split('=') // ['email', '1'] let key = parts[0] let value = parts[1] hash[key] = decodeURIComponent(value) // hash['email'] = '1' }) let { email, password } = hash var users = fs.readFileSync('./db/users', 'utf8') try { users = JSON.parse(users) // [] } catch (exception) { users = [] } let found for (let i = 0; i < users.length; i++) { if (users[i].email === email && users[i].password === password) { found = true break } } if (found) {// The key is here, verify successfully, Set the login Cookie as the login mailbox, and send it to the browser in response to response.setHeader(' set-Cookie ', `sign_in_email=${email}`) response.statusCode = 200 } else { response.statusCode = 401 } response.end() }) }

At the moment of successful login, it is necessary to set a Cookie in the background, record the login user ID (represented by email here, the code is above), and then send the response to the browser. For example, set the response header on the server side: set-cookies: [email protected]

At this point we look at the response:

A cookie has been set in the response header.

We then jump to the home page, where we view the request to jump to the home page:

The request header to the home page contains a cookie field (which will be carried with you when you visit this domain). So, as the previous article said:

If the server gives the browser a setcookie response header, then all subsequent requests from this browser, as long as they are from the same source (i.e., the same domain name and port that sent me the Cookie last time), will carry with them the Cookie that the server sent to this browser at that time

In the future, as soon as the browser accesses the path, the browser will attach the Cookie to the server

That is, for the first request, the server sets a Cookie for the browser. For the next request, the browser sends the Cookie to the server with the browser. The first time the server logs in, it sets a Cookie to the browser response. Set-cookies: User_email [email protected], and then the next time the browser makes a request, it finds a Cookie named user_email in the Cookie, and the domain name I sent the request to is the same domain name that was sent to me last time with the Cookie in response.

There is no need to log in again. The server sends the browser a ticket to the server the next time the browser enters the server or the next time the browser shows the server the ticket

The background reads the Cookie to retain the login status and deletes the Cookie to exit the login status

Home code:

The < body > < h1 > I am a home page < / h1 > < div class = "" > < a href =". / sign_up "> register < / a > < a href =". / sign_in "> login < / a > < / div > < h1 > your state is: __status__ < / h1 > < h1 > your email account is: __email__ < / h1 > < h1 > your password is: __password__ < / h1 > < a href = "javascript:;" Id = "logOffBtn" > log out (delete cookies) < / a > < / body > < script > logOffBtn. AddEventListener (" click ", () = > {/ / the only way to delete an existing cookies, Set its Expires property to a past date. document.cookie = 'sign_in_email=; expires=Thu, 01-Jan-1970 00:00:01 GMT' window.location = "/" }) </script>

Background routing code

if (path === '/') { response.statusCode = 200 let string = fs.readFileSync('./index.html') string = string.toString(); Var users = fs.readFileSync('./db/users', 'utf8') users = json.parse (users)// convert to user object array console.log(users); let cookies = request.headers.cookie || ''//['email=111', 'asdasd=111'] cookies = cookies.split("; ") let hash={} cookies.forEach((string)=>{ let parts = string.split("=") let key = parts[0] let value = parts[1] hash[key] = value; }) let eamil = hash.sign_in_email let foundedUser users.forEach((userObj)=>{ if(userObj.email===eamil){ foundedUser = userObj; } }) console.log(foundedUser); If (foundedUser){string = string.replace('__status__', 'logged in ') string = string.replace('__email__', foundedUser.email) string = string.replace('__password__', }else{string = string.replace('__status__', 'Please log in ') string = string.replace('__email__', Replace ('__password__', 'no ')} response.setHeader(' content-type ', 'text/ HTML; charset=utf-8') response.write(string) response.end() }

The state of the home page in the absence of cookies

After logging in, the background will query the database according to the Cookie and send the user name and password to the front page

Logging out will delete the Cookie and refresh the page to return to the unlogged state

Cookie characteristics at the time of login

We get the characteristics of cookies:

  1. The first time you log in, the server sets a Cookie through the Set-Cookie response header and sends it to the browser in the form of a response
  2. Once the browser gets the Cookie in response, it carries the Cookie with it every time it requests the domain name
  3. Then the server reads the Cookie set by itself at that time and knows the information of the login user (email).

A couple of questions about cookies

1. If you login in Chrome and get a Cookie, use Safari to access it. Safari does not carry a Cookie

2.Cookie which Windows stored in a C disk file

3. Will cookies be tampered with by users? Yes, for example, you can manually modify the application->Cookie in the developer mode of the Google browser. After modification, the next time you send a request, the modified Cookie will be attached

JS also has the API that can operate the cookie (if replaced by other users’ accounts, then you can also log in successfully, there will be a risk problem. Session to solve this problem, to prevent user tampering) the backend can be forced to not allow to modify the Cookie, as long as the Cookie attribute is set to HttpOnly (you can also manually change, but JS can not change, also can not obtain), the specific syntax is MDN 4. The default expiry date is around 20 minutes, with different browser policies (cookies will not be deleted if the browser is always open). If the browser is closed, the browser may delete the Cookie after 20 minutes or so for security reasons. It also depends on how the server sets the expiration date of the Cookie. The backend can force the expiration date of the Cookie. There is, but it’s a little different than the same origin policy with Ajax. When requesting resources under QQ.com, the browser will default to bring the Cookie corresponding to QQ.com, but will not bring the Cookie corresponding to Baidu.com. When requesting resources under V.QQ.com, the browser will not only bring the Cookie of V.QQ.com, In addition, cookies can also be restricted according to the path. Please understand by yourself. This function is rarely used.

Details to be paid attention to

Why do both front and back end forms validate?

The front and back end should verify whether the mailbox format is correct, whether the account password format is correct, whether the password submitted twice is the same, etc. For example, a hacker can directly use curl to send a request and interact with the backend server directly. As shown in figure:

So you also need to do form validation in the background.

How to turn off Cookie manually

translation

-Sheldon: I don’t know what the cookie is, and it’s in the cache control system