Front-end and back-end authentication (Session and JWT authentication mechanism)

1.1 Web development model

There are currently two mainstream web development models, namely:

①Based on 服务端渲染the traditional Web development model

前后端分离New Web development model based on

1 Server-side rendering

服务端渲染的概念: The HTML page sent by the server to the client is dynamically generated on the server by splicing strings. Therefore, the client does not need to use technologies such as Ajax to additionally request page data.

advantage:

前端耗时少. Because the server side is responsible for dynamically generating HTML content, the browser only needs to render the page directly. Especially the mobile terminal, more power saving.

有利于SEO. Because the server-side response is the complete HTML page content, it is easier for crawlers to crawl and obtain information, which is more conducive to SEO.

shortcoming:

①Occupy server-side resources . That is, the server side completes the splicing of HTML page content. If there are many requests, it will cause certain access pressure on the server.

It is not conducive to the separation of front and back ends , and the development efficiency is low. Using server-side rendering makes it impossible to carry out division of labor and cooperation, especially for projects with high front-end complexity, which is not conducive to efficient project development.

2 Separation of front and rear ends

The concept of front-end and back-end separation: the development model of front-end and back-end separation, 依赖于Ajax 技术的广泛应用.

In short, the Web development model with front-end and back-end separation is 后端只负责提供 API接口,前端使用 Ajax 调用接口的开发模式.

advantage:

开发体验好. The front end focuses on the development of UI pages, the back end focuses on the development of api, and the front end has more options.

用户体验好. The wide application of Ajax technology has greatly improved the user experience, and can easily achieve partial refresh of the page.

减轻了服务器端的渲染压力. Because the page is ultimately generated in each user's browser.

shortcoming:

Not conducive to SEO . Because the complete HTML page needs to be spliced ​​dynamically on the client side, the crawler cannot crawl the effective information of the page. (Solution: Using the SSR (server side render) technology of front-end frameworks such as Vue and React can solve SEO problems very well!)

3 How to choose a Web development model

Blindly choosing which development model to use without talking about business scenarios is hooliganism.

For example, an enterprise-level website whose main function is to display without complex interaction, and requires good SEO, then we need to use server-side rendering;

Similar to background management projects, the interactivity is relatively strong, and SEO does not need to be considered, so the development mode of front-end and back-end separation can be used.

In addition, it is not absolute which development mode to use. In order to take into account both the rendering speed of the homepage and the development efficiency of front-end and back-end separation , some websites adopt the development mode of first-screen server-side rendering + front-end and back-end separation of other pages.

1.2 Identity authentication

1 What is identity authentication

Authentication , also known as "identity verification" and "authentication", refers to the confirmation of the user's identity through certain means .

Identity authentication in daily life can be seen everywhere, for example: ticket checking for high-speed rail, mobile phone password or fingerprint unlocking, Alipay or WeChat payment password, etc.

In web development, authentication of user identity is also involved, such as: mobile phone verification code login , email password login , QR code login , etc. of major websites.

2 Why authentication is required

The purpose of identity authentication is to confirm that the user who currently claims to be a certain identity is indeed the claimed user . For example, if you go to the courier to pick up the courier, how do you prove that the courier is yours.

In the development of Internet projects, how to authenticate users' identities is a problem worthy of in-depth discussion. For example, how can we ensure that the website will not mistakenly display "Ma Yun's deposit amount" on "Ma Huateng's account".

3 Authentication Session and JWT under different development modes

For the two development modes of server-side rendering and front-end and back-end separation, there are different authentication schemes:

①Recommended 服务端渲染useSession 认证机制

②Recommended 前后端分离useJWT 认证机制

1.3 Session authentication mechanism

1 Statelessness of the HTTP protocol

Understanding the statelessness of the HTTP protocol is a necessary prerequisite for further study of the Session authentication mechanism.

The stateless nature of the HTTP protocol refers to the client's 每次 HTTP请求都是独立的, 连续多个请求之间没有直接的关系, 服务器不会主动保留每次HTTP请求的状态.

2 How to break through the stateless limitation of HTTP

For supermarkets, in order to facilitate cashiers to give discounts to VIP users during settlement, supermarkets can issue membership cards to each VIP user.

Note: The membership card authentication method in real life is called in the professional term in Web development Cookie.

The cookie is the identification of identity authentication.

3 What is a cookie

Cookieis a string of no more than 4kb stored in the user's browser. That is, a key-value pair

It consists of a name, a value, and several optional attributes used to control the cookie's validity period, security, and scope of use.

会自动把当前域名下所有未过期的 CookieCookies under different domain names are independent, and they are sent to the server together when the client initiates a request .

Several characteristics of cookies:

①Send automatically

② Independent domain name

③ Expiration time limit

④4KB limit

4 The role of cookies in identity authentication

When the client requests the server for the first time, the server sends an authentication cookie to the client in the form of a response header, and the client automatically saves the cookie in the browser.

Subsequently, when the client browser requests the server each time, the browser will automatically send the cookie related to identity authentication to the server in the form of a request header, and the server can verify the identity of the client.

When the client initiates a login request, the server will send the cookie to the client browser through the request header.

Save to the browser for identity authentication.

When the client sends a request again, the cookie is automatically sent to the server through the request header.

The server verifies the identity of the user based on the Cookie in the request header. Respond to the corresponding content of the current user.

5 Cookies are not secure

Since cookies are stored in the browser and, 浏览器也提供了读写Cookie的 APItherefore Cookie很容易被伪造, are not secure. Therefore, it is not recommended that the server send important private data to the browser in the form of cookies.

Note: 千万不要使用 Cookie 存储重要且隐私的数据! Such as user identity information, password, etc.

6 Provide security for identity authentication

In order to prevent customers from forging membership cards, the cashier can swipe the card for authentication on the cash register after receiving the membership card presented by the customer. Only the membership card confirmed by the cash register can be used normally.

会员卡 + 刷卡认证This design concept is the essence of the Session authentication mechanism.

You can't just rely on the cookie presented by the user for authentication, but you also need to perform cookie authentication on the server side.

The identity can be determined only after the server-side cookie authentication is passed.

The membership card means the client presents the cookie

Swipe card authentication means identity authentication on the server side

7 How Sessions work

1.4 Using Session Authentication in Express

1 Install express-session middleware

In the Express project, you only need to install the express-session middleware to use Session authentication in the project:

npm install express-session 

2 Configure express-session middleware

After the express-session middleware is successfully installed, you need to register the session middleware through app.use(). The sample code is as follows:

// TODO_01:请配置 Session 中间件
const session = require("express-session");
app.use(
  session({
    
    
    secret: "sessionabc",
    resave: false,
    saveUninitialized: true,
  })
);

3 Store data in the session

After the express-session middleware is configured successfully, the session object can be req.sessionaccessed and used to store key user information:

  // TODO_02:请将登录成功后的用户信息,保存到 Session 中
  // 注意: 只有成功配置了 express-session 这个中间件之后,才能够通过 req 点出来 session 这个属性
  req.session.user = req.body; // 用户信息
  req.session.islogin = true; // 用户的登录状态

4 Get data from session

The previously stored data can be obtained directly from req.sessionthe object , the sample code is as follows:

  // TODO_03:请从 Session 中获取用户的名称,响应给客户端
  if (!req.session.islogin) {
    
    
    return res.send({
    
     status: 1, msg: "fail" });
  }
  res.send({
    
    
    status: 0,
    msg: "success",
    username: req.session.user.username,
  });

5 clear session

Call req.session.destroy()the function to clear the session information saved by the server.

  // TODO_04:清空 Session 信息
  req.session.destroy();
  res.send({
    
    
    status: 0,
    msg: "成功退出",
  });

1.5 JWT authentication mechanism

1 Understand the limitations of Session authentication

Session 认证机制需要配合 Cookie 才能实现。

由于 Cookie 默认不支持跨域访问, so, when designing the front-end cross-domain request to the back-end interface, 需要做很多额外的配置,才能实现跨域 Session 认证.

Notice:

When the front-end requests the back-end interface and there is no cross-domain problem , it is recommended to use the Session authentication mechanism.

At the time of the current front-end 需要跨域请求后端接口, it is not recommended to use the Session authentication mechanism 推荐使用 JWT 认证机制.

2 What is JWT

JWT (English full name: JSON Web Token) is currently 最流行available 跨域认证解决方案.

3 How JWT works

Summary: User information is stored in the client browser in the form of Token strings. The server authenticates the user's identity by restoring the form of the Token string.

4 Components of JWT

JWT usually consists of three parts, namely Header(头部), Payload(有效荷载), Signature(签名).

Used between the three 英文的“.”分隔, the format is as follows:

Header,Payload,Signature

What do the three parts mean:

PayloadPart is 真正的用户信息, it is a string generated after user information is encrypted.

Header and Signature are 安全性相关the only parts, just to ensure the security of Token.

5 How to use JWT

After the client receives the JWT returned by the server, it usually sends it 储存在 localStorage 或 sessionStorage 中.

Since then, every time the client communicates with the server, it must bring this JWT string for identity authentication.

The recommended practice is 把JWT放在HTTP 请求头的Authorization字段中that the format is as follows:

Authorization: Bearer <Token>

1.6 Using JWTs in Express

1 Install JWT related packages

Install the following two JWT related packages

npm install jsnwebtoken express-jwt

in:

jsonwebtokenUsed to generate the JWT string

express-jwtUsed to parse and restore JWT strings into JSON objects

2 Import JWT related packages

Use the require() function to import two packages related to WT:

// TODO_01:安装并导入 JWT 相关的两个包,分别是 jsonwebtoken 和 express-jwt

// 1 导入用于生成 JWT 字符串的包
const jwt = require("jsonwebtoken");

// 2 导入用于将客户端发送过来的 JWT 字符串,解析还原成 JSON 对象的包
const expressJWT = require("express-jwt");

3 Define the secret key

In order to 保证 JWT 字符串的安全性prevent the JWT string from being cracked by others during network transmission, we need to define a secret key for encryption and decryption :

1 When generating the JWT string, you need to use the secret key to pair the user's information 进行加密, and finally get the encrypted JWT string

2 When parsing and restoring the JWT string into a JSON object, you need to use the secret key进行解密

// TODO_02:定义 secret 密钥,建议将密钥命名为 secretKey

// secret 秘钥本质:就是一个字符串 (字符串为任意字符,越复杂越好)
const secret = 'jwt secret 2022'

4 Generate JWT string after successful login

Call the methodjsonwebtoken provided by the package , encrypt the user's information into a JWT string, and respond to the client:sign()

// TODO_03:在登录成功之后,调用 jwt.sign() 方法生成 JWT 字符串。并通过 token 属性发送给客户端

// 参数1:用户的信息对象 { username: userinfo.username }
// 参数2:加密秘钥 secretKey
// 参数3:配置对象,可以配置当前 token 的有效期 { expiresIn: "30s" }
// 记住:千万不要把密码加密到 token 字符串中  
 const tokenStr = jwt.sign(
      {
    
     username: userinfo.username }, 
      secretKey, 
      {
    
     expiresIn: "30s" }
  );

  res.send({
    
    
    status: 200,
    message: "登录成功!",
    token: tokenStr, // 要发送给客户端的 token 字符串
  });

5 Revert the JWT string to a JSON object

Every time the client accesses those authorized interfaces, it needs to actively pass through 请求头中的Authorization字段and send the Token string to the server for identity authentication.

At this point, the server can automatically parse and restore the Token sent by the client into a JSON object through express-jwtthis middleware:

// TODO_04:注册将 JWT 字符串解析还原成 JSON 对象的中间件

// 使用 app.use() 来注册中间件
// expressJWT({ secret:secretKey }) 就是用来解析 token 的中间件
// .unless({path:[/^\/api\//]}) 用来指定哪些接口不需要访问权限
app.use(expressJWT({
    
     secret: secretKey }).unless({
    
     path: [/^\/api\//] }));

// 注意:只要配置成功了 express-jwt 这个中间件,,就可以把解析出来的用户信息,挂载到 req.user 属性上

6 Use req.user to get user information

After express-jwtthe middleware is successfully configured, you can use req.userthe object in those authorized interfaces to access the user information parsed from the JWT string. The sample code is as follows:

// 这是一个有权限的 API 接口
app.get("/admin/getinfo", function (req, res) {
    
    
  // TODO_05:使用 req.user 获取用户信息,并使用 data 属性将用户信息发送给客户端
  console.log(req.user);
  res.send({
    
    
    status: 200,
    message: "获取用户信息成功!",
    data: req.user, // 要发送给客户端的用户信息
  });
});

7 Capture errors generated after parsing JWT fails

When using express-jwtto parse the Token string, if the Token string sent by the client is expired or illegal , an error of parsing failure will be generated , which will affect the normal operation of the project.

We can use Express 's error middleware to capture this error and perform related processing. The sample code is as follows:

// TODO_06:使用全局错误处理中间件,捕获解析 JWT 失败后产生的错误
// 在所有路由之后,配置全局捕获错误中间件
app.use((err, req, res, next) => {
    
    
  // token 解析失败导致的错误
  if (err.name === "UnauthorizedError") {
    
    
    return res.send({
    
    
      status: 401,
      message: "无效的token",
    });
  }

  // 其他原因导致的错误
  return res.send({
    
    
    status: 500,
    message: "未知错误",
  });
});

affect the normal operation of the project.

We can use Express 's error middleware to capture this error and perform related processing. The sample code is as follows:

// TODO_06:使用全局错误处理中间件,捕获解析 JWT 失败后产生的错误
// 在所有路由之后,配置全局捕获错误中间件
app.use((err, req, res, next) => {
    
    
  // token 解析失败导致的错误
  if (err.name === "UnauthorizedError") {
    
    
    return res.send({
    
    
      status: 401,
      message: "无效的token",
    });
  }

  // 其他原因导致的错误
  return res.send({
    
    
    status: 500,
    message: "未知错误",
  });
});

Guess you like

Origin blog.csdn.net/qq_53931766/article/details/127515695