[Database | MySQL] Front-end and back-end authentication

One: web development model

1: Web development model based on server-side rendering

The concept of server-side rendering: The HTML page sent by the server to the client is dynamically generated by the server through the splicing of strings. Therefore, the client does not need to use technologies such as Ajax to request additional page data.

Advantages:
① The front end consumes less time. Because the server is responsible for dynamically generating HTML content, the browser only needs to directly render the page. Especially the mobile terminal, more power saving.

② Conducive to SEO. Because the server responds to the complete HTML page content, it is easier for crawlers to crawl to obtain information, which is more conducive to SEO.

Disadvantages:
① 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 rear ends, and the development efficiency is low. If server-side rendering is used, division of labor cannot be carried out, especially for projects with high front-end complexity, which is not conducive to efficient project development

2: Web development model with separation of front and back ends

The concept of front-end and back-end separation: the development model of front-end and back-end separation depends on the wide application of Ajax technology. In short, the web development model with separation of front and back ends means that the back end is only responsible for providing API interfaces, and the front end uses Ajax to call the interface.
1
Advantages:
① Good development experience. 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.

② Good user experience. The wide application of Ajax technology greatly improves the user experience and can easily achieve partial refresh of the page.

③ Reduce the rendering pressure on the server side. Because the page is ultimately generated in each user's browser.

Disadvantages:
① Not conducive to SEO. Because the complete HTML page needs to be dynamically spliced ​​on the client, the crawler cannot crawl the effective information of the page.

(Solution: SSR (server side render) technology using front-end frameworks such as Vue and React can solve SEO problems very well!)

3: How to choose a web development model

  • For example, an enterprise-level website, whose main function is to display without complicated interaction, and requires good SEO, then we need to use server-side rendering at this time;
  • And similar to the back-end management project, the interaction is relatively strong, no need to consider SEO, then you can use the development model of separation of front and back ends.
  • In addition, the specific development mode used is not absolute. In order to take into account both the rendering speed of the homepage and the development efficiency of front-end separation, some websites adopt the development model of first-screen server-side rendering + front-end separation of other pages.

2: Identity authentication

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, such as: high-speed rail ticket inspection, mobile phone password or fingerprint unlocking, Alipay or WeChat payment password, etc.
  • In Web development, user identity authentication is also involved, such as: mobile phone verification code login, mailbox password login, QR code login, etc. of major websites.

2: Identity authentication under different development modes

For server-side rendering and front-end separation, there are different authentication schemes respectively:
① Session authentication mechanism is recommended for server-side rendering
② JWT authentication mechanism is recommended for front-end and back-end separation

3: Statelessness of HTTP protocol

The statelessness of the HTTP protocol means that each HTTP request of the client is independent, and there is no direct relationship between multiple consecutive requests, and the server will not actively retain the status of each HTTP request.
2

4: How to break the limit of HTTP stateless

3
For supermarkets, in order to facilitate cashiers to discount VIP users during settlement, the supermarket can issue membership cards for each VIP user.

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

4.1: What is a cookie

Console: application——>cookies (composed of key value)

A cookie is a string of no more than 4 KB stored in the user's browser. It consists of a name (Name), a value (Value) and several other optional attributes that are used to control the validity period, security, and scope of the cookie.

Cookies under different domain names are independent. Whenever a client initiates a request, it will automatically send all unexpired cookies under the current domain name to the server.

Several major characteristics of cookies:
① Automatic sending
② Independent domain name
③ Expiration time limit
④ 4KB limit

5

4.2: 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, each time the client browser requests the server, 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.
6

4.3: Cookies are not secure

Because cookies are stored in the browser, and the browser also provides APIs for reading and writing cookies, cookies can be easily forged and are not secure. Therefore, it is not recommended that the server send important privacy data to the browser in the form of cookies.
7
Never use cookies to store important and private security issues

7

5: Session authentication mechanism

5.1: Improve the security of identity authentication

In order to prevent customers from forging membership cards, cashiers can perform card 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.
6
The design concept of membership card + credit card authentication is the essence of session authentication mechanism

5.2:

9

  1. Install express-session middleware
    In the Express project, you only need to install express-session middleware to use Session authentication in the project:
npm install express-session
  1. Configure express-session middleware After the
    express-session middleware is successfully installed, you need to register the session middleware through app.use().
//导入session中间件
const session=require('express-session')

//配置中间件
app.use(session({
    
    
	secret:'keyboard cat',//属性值可以为任意字符
	resave:false,//固定写法
	saveUninitialized:true //固定写法
	}))
  1. Store data in the session
    When the express-session middleware is successfully configured, you can access and use the session object through req.session to store the key information of the user:
app.post('/api/login',(req,res)=>{
    
    
	//判断用户提交的登录信息是否正确
	if(req.body.username !=='admin' || req.body.password !=='000000'){
    
    
		return res.send({
    
    status:1,msg:'登陆失败'})
	}
	req.session.user=req.body //将用户的信息存储在session中
	req.session.isogin=true //将用户登录状态,存储在session中

	res.send({
    
    status:0,msg:'登陆成功'})
})

  1. Get data from the session You can get the previously stored data directly from the req.session object,
app.get('/api/username',(req,res)=>{
    
    
	//判断用户是否登录
	if(!req.session.islogin){
    
    
		return res.send({
    
    status:1,msg:'登陆失败'})
	}
	res.send({
    
    status:0,msg:'登陆成功',username:req.session.user.username})
	
  1. To clear the session,
    call the req.session.destroy() function to clear the session information saved by the server.
app.post('/api/logout',(req,res)=>{
    
    
	//清空当前客户端对应的session
	req.session.destroy()
	res.send({
    
    
		status:0,
		msg:'退出登录成功'
		})
	})

6: JWT authentication mechanism

6.1: Understand the limitations of Session authentication

Session authentication mechanism needs to cooperate with Cookie to realize. Because cookies do not support cross-domain access by default, when it comes to front-end cross-domain requests to back-end interfaces, a lot of additional configuration is required to achieve cross-domain session authentication.

note:

  • When the front-end request back-end interface does not have cross-domain problems, it is recommended to use the Session authentication mechanism.
  • When the front end needs to request a back-end interface across domains, it is not recommended to use the Session authentication mechanism, and it is recommended to use the JWT authentication mechanism.
6.2: What is JWT

JWT (English name: JSON Web Token) is currently the most popular cross-domain authentication solution.

token:
cookie data, in the case of cross-domain,
session will not be automatically carried and will occupy server-side resources, cross-domain is not supported

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

6.3: The components of JWT

JWT usually consists of three parts, namely Header (header), Payload (payload), Signature (signature).

Use the English "." to separate the three,

The Payload part is the real user information, which is a character string generated after user information is encrypted.

Header and Signature are security-related parts, just to ensure the security of Token.

header.Payload.Signature
6.4: Use of JWT

After the client receives the JWT returned by the server, it usually stores it in localStorage or sessionStorage.

After that, every time the client communicates with the server, it must bring this JWT string for identity authentication. The recommended approach is to put the JWT in the Authorization field of the HTTP request header,

//请求头的Authorization
Authorization:Bearer <token>
  1. Install JWT-related packages
    Run the following command to install the following two JWT-related packages:
npm install jsonwebtoken express-jwt

jsonwebtoken is used to generate JWT strings

express-jwt is used to parse JWT strings into JSON objects

  1. Import JWT-related packages
    Use the require() function to import two JWT-related packages:
//导入用于生成JWT字符串的包
const jwt = require( ' jsonwebtoken ')
//导入用于将客户端发送过来的JWT字符串,解析还原成JSON对象的包
const expressJWT = require('express-jwt ')
  1. Defining the secret key
    In order to ensure the security of the JWT string and prevent the JWT string from being cracked by others during network transmission, we need to specifically define a secret key for encryption and decryption:
    ① When generating the JWT string, You need to use the secret key to encrypt the user's information, and finally get the encrypted JWT string
    ② When the JWT string is parsed and restored into a JSON object, the secret key needs to be used for decryption
//secret密钥的本质:就是一个字符串
const secretKey = 'hello'
  1. Generate a JWT string after successful login.
    Call the sign() method provided by the jsonwebtoken package to encrypt the user’s information into a JWT string, and respond to the client
//登录接口
app.post( " lapi/login' , function( req, res){
    
    
//...省略登录失败情况下的代码
//用户登录成功之后,生成JMT字符串,通过token属性响应给客户端
res.send({
    
    
	status: 200,
	message: '登录成功! '//调用jwt , sign()生成JWT字符串,三个参数分别是:用户信息对象、加密密钥、配置对象
	token: jwt.sign({
    
     username: userinfo.username }, secretKey,{
    
     expiresIn: '30s' })10}
 })
  1. Restore the JWT string to a JSON object
    . Each time the client accesses those authorized interfaces, it needs to actively send the Token string to the server for identity authentication through the Authorization field in the request header.
    At this point, the server can automatically parse and restore the Token sent by the client into a JSON object through the express-jwt middleware:
//使用app.use()来注册中间件
//expressJMT({ secret: secretKey })就是用来解析Token的中间件
//.unless({ path: [ /A\/api\//]})用来指定哪些接口不需要访问权限
app.use(expressJwT({
    
     secret: secretKey }).unless({
    
     path: [ /A\/api\//] }))
  1. Use req.user to get user information.
    After the express-jwt middleware is successfully configured, you can use the req.user object in those authorized interfaces to access the user information parsed from the JWT string, sample code as follows:
//这是一个有权限的API接口
app·get( ' l admin/getinfo', function(req, res){
    
    
	console.log(req.user)
	res.send({
    
    
		status: 200,
		message: "获取用户信息成功! ',
		data: req.user
	})
})
  1. Capture the error generated after the failure to parse the JWT
    When using express-jwt to parse the Token string, if the Token string sent by the client is out of date or illegal, a parsing failure error will be generated, which will affect the normal operation of the project. We can catch this error and deal with it through Express's error middleware. The sample code is as follows:
app.use((err, req,res,next) =>{
    
    
	//token 解析失败导致的错误
	if(err.name === 'UnauthorizedError '){
    
    
		return res.send({
    
     
			status: 401,message: '无效的token'
			 })
		}
		//其它原因导致的错误
	res.send({
    
     status: 500,message: '未知错误·})
}

I'll add it in a few days...

Guess you like

Origin blog.csdn.net/qq_43490212/article/details/113068552