📍 Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Authentication is an essential part of the login at the front and back ends. It plays an important role. The following describes several common authentication methods at the front and back ends

Cookie

Cookie is the data (usually encrypted) stored on the user’s local terminal by some websites to identify the user’s identity, and the information temporarily or permanently saved by the user client

A Cookie is essentially a string that is stored in the client’s hard disk or memory as key-value pairs (set Cookie expiration time in the hard disk, otherwise in memory). In general, it is used to determine whether two requests are from the same browser, for example, the user remains logged in.

The Domain and Path in the Cookie define the scope of the Cookie: that is, the URL to which the Cookie should be sent.

The Domain identifier specifies which hosts can accept cookies. If this parameter is not specified, the current host (excluding the subdomain name) is used by default. If Domain is specified, subdomain names are generally included.

Note: cookies are generally used to store user login information and cannot exceed 4KB in size

Session

In Web development, sessions are usually used to complete session tracking. Because the server assigns a unique sessionId as the cookie of the client as the identification, the underlying session relies on cookie technology

The HTTP request is stateless, that is, the server normally does not know which client is the source of the current request. When the client makes the first request, the server will start a session to record the current user’s status and return a sessionId -sessionId to the client. When the client accesses the cookie next time, it carries the sessionId, and the server obtains the sessionId to find the corresponding session.

You can see the saved sessionID in the Cookie of the gold digging page:

To prevent memory overflow caused by too many sessions on the server, the Web server sets a validity period for each session by default. If the client does not access the session during the validity period, the web server considers the client offline and deletes the session.

Token

A Token is a Token that consists of user information, a timestamp, and an algorithmically encrypted signature. It is used to uniquely identify a client.

The advantage of the token

1. Stateless and extensible

2. Support mobile devices

3. Cross-program invocation

4. Security

Since each request requires the token to be placed in the HTTP Headers, we can carry the token in the header using the AXIOS request interceptor

if (store.getters.token) {
  config.headers['X-Token'] = getToken()
}
return config
Copy the code

Token authentication process

  1. The client logs in with the user name and password
  2. After the authentication, the server generates a token and sends it to the client
  3. After receiving the token, the client saves the token in a Cookie or local storage
  4. When a client requests data, it carries a token in the HTTP request header
  5. After verifying the token, the server returns data to the client

JWT

JWT(Json Web Token) is a Token specification defined in RFC 7519. It defines a concise, self-contained protocol format for transmitting Json objects between communication parties. The information transmitted can be verified and trusted through digital signatures. JWT can be signed using the HMAC algorithm or using RSA’s public/private key pair to prevent tampering.

The advantages of JWT

  • Json based, easy to parse
  • Customizable content, easy to expand
  • Based on asymmetric algorithm and digital signature, high security

The composition of JWT

The JWT consists of Header, Payload, and Signature. Space,

The Header is usually generated using the commonly used HS256 or RS512 encryption algorithms

Payload Indicates the field required for transmission

Signature is a character string encrypted by the algorithm and the SECRET_KEY

JWT is usually saved using local storage

Get started with JWT

The installation

npm i -S jsonwebtoken
Copy the code

Use (pseudocode)

const jwt = require('jsonwebtoken')
const PRIVATE_KEY = 'secretkey'    // JWT private key user-defined
const JWT_EXPIRED = 60 * 60    / / 1 hour

login(username, password).then(user= > {
    if(! user || user.length ===0) {
      // Login failed
    } else {
      const token = jwt.sign(
        { username },
        PRIVATE_KEY,
        { expiresIn: JWT_EXPIRED }
      )
      / / token}})Copy the code

More information about JWT can be found on the JWT website