Vue JWT time extension problem

Time:2020-5-14

Vue JWT time extension problem

jwt(json web token)

  • You need to install the body parser (parsing request body), jsonwebtoken (creating token)


Our idea is to log in with an admin account written on the login page, and the server will send it a token, and then carry the token with each request of the client to the server for verification.
Let’s write an interface with express first

let secret = 'qc'
app.post('/login', (req, res) => {
  let {
    username
  }= req.body; // request body to put body
  if (username == 'admin') {
    res.json({
      code: 0,
      username: 'admin',
      //Generate the token jwt.sign (generated things, secret key, {settings}), send it to the client, save it, bring it with each request, and the server will check whether the token is brought with each time 
      token: jwt.sign({
        username: 'admin'
      }, secret, {
        Expires in: 1000 // token expiration time
      })
    })
  } else {
    res.json({
      code: 1,
      Data: 'user name does not exist'
    })
  }
})

This interface completes a verification of the login input time of admin and then returns the user name and token to you
The client receives the token, stores it in localstorage, and then brings each request in the Axios interceptor

instance.interceptors.request.use((config)=>{ 
      //Generally, token is added to the change request header
      config.headers.Authorization=getlocal('token')
      return config
    }),

In this way, every time we request an interface, we will bring a token. Next, we are writing a verification token interface on the server

let jwt = require('jsonwebtoken')
app.get('/validata', (req, res) => {
  let token = req.headers.authorization ; // remove the token from the request header
  Jwt.verify (token, secret, (err, decode) = > {// jxt.verify method. The parameters are (token, the secret key set by yourself. The execution result is put in decode.
    if (err) {
      return res.json({
        code: 1,
        Data: 'token failed'
      })
    } else {
      //If the verification passes, a new token is sent to the client to extend the token time.
      res.json({
        //Need to extend the time limit of token
        username: decode.username,
        code: 0,
        token: jwt.sign({
          username: 'admin'
        }, secret, {
          expiresIn: 20
        })
      })
    }
  }) // decode is equal to the username: admin set by itself
})

Then we call this method through the switch path of the client to make the user think online as long as he / she is operating the switch page, so that the token does not fail
In addition, if each component needs to have this method, we need to put it in vuex.

//Action configuration in vuex.
actions: {
      async validata({commit}){
          let res = await validata()
          console.log(res);
          if(res.code==0 ){
            commit('setUser',res.username)
            setlocal('token',res.token)
          }
          return res.code==0
      }
  }

  //Global route monitoring is achieved by routing beforeeach.    
router.beforeEach(async (to,from,next)=>{
   let islogin =await store.dispatch('validata') 
   
})

Summary: when the client logs in for the first time, the server returns a token to the client. The client carries this token every time it requests. When the user switches routes, he calls a verification interface of the server every time. If the verification is successful, the token time will be extended.