Talking about Session, Cookie and token

1. Session

Reference link
Reference link

1. The origin of Session

Because the http protocol is stateless, it cannot remember the user's state. So what is stateless? That is to say, this request has nothing to do with the previous request, they don't know each other, and they are not related.

For example: just entered the user name and password, and the request successfully jumps to the shopping cart. When you want to add items to the shopping cart, you will be prompted to log in to use it (this is the function of the routing guard~), when you enter the user name and password again After that, click Add to Cart or prompt to log in. This is statelessness.

This was no problem before, but with the rise of interactive web applications, such as shopping websites or websites that require login, etc., session management is required, so session identification (session id) appears.

The role of session id is actually to track user status and distinguish users.

2. Working principle of Session

The user requests the server for the first time

  1. Send a request to the server, and the server opens up a memory space to save all session objects on the server side, and each session object will have a unique session id.
  2. The server returns the session id to the browser (in the set-cookie of the response header), and the browser will use the cookie to store the session ID by default. If the browser disables the cookie, you can use the url method (not commonly used) .
  3. Subsequent requests will carry the session id in the cookie (name is jsession, value is session id) in the request header, and the server will check whether there is a session corresponding to the session id.

The sessionId execution of the session depends on the cookie, but not only the cookie, but also LocalStorage or URL writeback to the server.

Session and Cookie

session: The server will generate a session object for the first requesting user, and have a session id corresponding to it, save it in memory and return it to the browser; when the client sends the request again, it will save the session id, the server will find the corresponding Session object according to the Session id after receiving the request, and use it again.
Cookie: The session id received by the browser can be saved to the browser through a cookie.
token: It is another solution to solve the statelessness of the http protocol through verification. It uses the verification mechanism and can also be saved with cookies or local storage, which will not be expanded here.

2. Cookies

Cookie is an integral part of the request header in the HTTP protocol. It is an objective text data with a small size. Cookie exists in the client, so it can be cleared by our browser (client). HTTP is stateless (accurately it should be HTTP1.0).

1.2 Composition of cookies

The name of the cookie
The value of the cookie (the real data is written in it)
The expiration time (it will be invalid after this time)
The domain name to which it belongs (the default is the current domain name)
The effective path (the default is the current URL)

1.3 Generation of cookies

1.2 Session cookies and persistent cookies

  • If the expiration time is not set, it means that the cookie life cycle is during the browser session, as long as the browser window is closed, the cookie will disappear. Such cookies whose lifetime lasts for the browsing session are called session cookies. Session cookies are generally not saved on the hard disk but in memory.

  • If the expiration time is set, the browser will save the cookie to the hard disk, and then open the browser again after closing, these cookies will still be valid until the set expiration time is exceeded.

Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different handling methods.

Is the life cycle of session cookie and session object the same?
When the user closes the browser, although the session cookie has disappeared, the session object is still saved on the server side.

reference link

2. js-cookie

JavaScript Cookie is a simple, lightweight JavaScript API dedicated to handling cookies.

2. js-cookie feature

  • Works with any browser
  • accept all characters
  • Rigorously tested
  • no dependency
  • Support JSON
  • AMD/CommonJS support
  • Compliant with RFC 6265
  • Support custom encoding/decoding
  • About 900 bytes compressed!

3. How to use

3.1 Installation

npm i [email protected]

3.2 Introduction

import Cookie from 'js-cookie'

3.3 use
3.3.1 Add
// 创建一个名称为name,对应值为value的cookie,由于没有设置失效时间,默认失效时间为浏览器会话结束,即关闭浏览器
Cookies.set(name, value)

// 创建一个有效时间为7天的cookie
Cookies.set(name, value, {
    
     expires: 7 })

// 创建一个带有路径的cookie
Cookies.set(name, value, {
    
     path: '' })

// 创建一个value为对象的cookie
const obj = {
    
     name: 'ryan' }
Cookies.set('user', obj)
3.3.2 Get
// 获取指定名称的cookie
Cookies.get(name) // value

// 获取value为对象的cookie
const obj = {
    
     name: 'ryan' }
Cookies.set('user', obj)
// 把字符串转回js对象
JSON.parse(Cookies.get('user'))

// 获取所有cookie
Cookies.get()
3.3.3 Delete
// 删除指定名称的cookie
Cookies.remove(name) // value

// 删除带有路径的cookie
Cookies.set(name, value, {
    
     path: '' })
Cookies.remove(name, {
    
     path: '' })

Reference link
Reference link

3. Token

1. The origin of Token

Token is generated to make up for the defects of Session and Cookie:

  • The server is under too much pressure and needs to store the session id of all requesting users
  • Insecure, cookies may be hijacked, causing.

2. The process of the user's first request to log in to the server

  1. Carry the user name and password or other identity information to the server to request login
  2. The server receives and verifies the username and password . If successful, it will use some algorithms on the data (username and password) to generate a signature (sign), and form a token (a string of strings) together with the data, also called a token; return a response to the browser device, token in
  3. The browser receives the response and stores the token locally (use localStorage for persistence, you can also use other methods, such as cookie, sessionStorage); each subsequent request will carry the token in the request header and send it to the server
  4. The server decrypts and recalculates the token, and if the generated new token is the same as the one sent by the browser, the verification passes

Guess you like

Origin blog.csdn.net/kwroi/article/details/128092860