Identity authentication in different development modes

  1. Session authentication is recommended for server rendering
  2. JWT authentication is recommended for separating the front and rear ends

Cokkie know

The process by which a supermarket cashier issues you a membership card and then shows it is similar to a cookie

The server issues cookies after the first successful login

  1. Cookies are strings stored in the user’s browser
  2. Domain independent
  3. Expiration time limit
  4. 4 KB limit

The role of cookies in identity authentication

Description:

  1. When a client requests the server for the first time, the server sends a Cookie to the client through the Response Headers, and the client saves the Cookie in the browser
  2. When the client requests the browser each time, the browser automatically carries cookies and sends them to the server through the Request Headers for identity authentication

Improve the security of identity authentication

Session authentication mechanism and working principle

Use Session authentication in Express

Install the Express-Session middleware

Configure express-session via app.use()

const session= require('express-session')
app.use(session({
  secret:'ztlovety'.// The secret attribute can be any string
  resave:false.saveUninitialized:true   // Save the uninitialization
}))
Copy the code

Into the sessoinSave the data

After the express-Session middleware is configured successfully, req. Session is used to access and store user information

app.post('/api/login'.(req, res) = > {
  // Check whether the login information submitted by the user is correct
  if(req.body.username ! = ='admin'|| req.body.password ! = ='000000') {
    return res.send({ status: 1.msg: 'Login failed'})}// TODO_02: Please save the user information after successful login to the Session
   req.session.user=req.body  // Tell the user information. Stored in Session
   req.session.islogin =  true  // Store the user login status in the Session

  res.send({ status: 0.msg: 'Login successful'})})Copy the code

Fetch data from session

app.get('/api/username'.(req, res) = > {
  // TODO_03: Please get the user name from the Session and respond to the client
  if(! req.session.islogin) {return res.send({status:1.msg:'fail'})
  }
  res.send({
    status:0.msg:'success'.username:req.session.user.username
  })
})
Copy the code

Clear the session

app.post('/api/logout'.(req, res) = > {
  // TODO_04: clears Session information
  req.session.destroy()
  res.send({
    status:0.msg:'Logged out successfully'})})Copy the code

JWT authentication mechanism

  1. Understand the limitations of Session authentication

Conclusion:

Session authentication is not used across domains

Use JWT authentication across domains

How JWT works

Session: Data is stored on the server

Token: Data is stored on the client

JWT component

JWT consists of Header, Payload, and Signature.

User information is encrypted and stored in the Payload section

How to use JWT

The client receives the JWT returned by the server after the local storage

Each time a request is made, it carries a JWT string, and it’s recommended that JWT be placed in the Authorization of the HTTP request header

 Authorization:Bearer <token>
Copy the code

The use of JWT

Install the packages associated with JWT

 npm install jsonwebtoken express-jwt

Copy the code
  • Jsonwebtoken is used to generate JWT strings
  • Express-jwt is used to parse and restore JWT strings into JSON objects. // The JWT sent by the client is parsed in JSON on the back-end server

Import jWT-related packages

const jwt =require('jsonwebtoken')
const expressJWT = require('express-jwt')
Copy the code

Defining the secret key

 const secretKey = 'ztyyds no1'
Copy the code

The secret key is essentially a string

Generate a JWT string after a successful login

The call provided by the jsonWebToekn package encrypts the user’s information into a JWT string in response to the client

// Call jwt.sign() to generate the JWT string. The three parameters are the user information object, the encryption key, and the configuration object

 token: jwt.sign({username:userinfo.username}, secretKey, {expiresIn:'30s'})
Copy the code

Restore the JWT string to a JSON object

 app.use(expressJWT({secret:secretKey}).unless({path: [/^\/api\//]}))
Copy the code

The req.user command is used to obtain user information

After the express. JWT middleware is configured successfully, the req. User object is used in the authorized interface to access the user information parsed in the JWT string

JWT – Catch error ’caused by failure to parse JWT

app.use((err,req,res,next) = >{
 if(err.name === 'UnauthorizedError') {return res.send({
     status:401.message:'Invalid token'
   })
 }
 res.send({
   status:401.message:'Unknown error'})})Copy the code