Save token after successful login verification in Vue and carry and verify token operation every time request

  • 2021-08-12 01:54:07
  • OfStack

In vue, you can use **Storage (sessionStorage, localStorage) ** to store token or vuex (but to consider the disappearance of page refresh data, you can use Storage in vuex).

Here's how to store it with localStorage:

After the login request is successful, it will return 1 token value and save it with loaclStorage

localStorage.setItem('token',res.data.token)

Setting global request header and response return judgment in main. js


// Settings axios Request header join token
Axios.interceptors.request.use(config => { 
 if (config.push === '/') { 
  } else { 
   if (localStorage.getItem('token')) { 
     // Add in the request header token The name should be the same as that of the backend receiving the request header token Name 1 Sample  
     config.headers.token=localStorage.getItem('token');  
   } 
  } 
   return config; 
 }, 
 error => { 
  return Promise.reject(error);
 });

//=============================
// Respond back token Expired or not 
Axios.interceptors.response.use(response => { 
  console.log(' Respond back: '+response.data.code) 
  // And back end token Failure return code convention 403 
  if (response.data.code == 403) {
    //  Quote elementui message Prompt box   
    ElementUI.Message({  
     message: ' Identity has expired ', 
     type: 'err'  
     });
    // Clear token 
    localStorage.removeItem('token ');
    // Jump   
    router.push({name: 'login'}); 
   } else { 
     return response 
   } 
  }, 
 error => { 
  return Promise.reject(error); 
  })

index in router sets the global guard to judge whether token exists or not, and returns to the login page if token does not exist


router.beforeEach((to, from, next) => {
//to Where to  from Where to leave  next Jump   If it is empty, it will be released  
 if (to.path === '/') {
 // If you jump to login, you will be released  
 next(); 
 } else {
 // Take out localStorage Judge 
  let token = localStorage.getItem('token ');   
  if (token == null || token === '') { 
    console.log(' Please log in first ')  
    next({name: 'login'});
   } else {
     next(); 
   } 
}});

Additional knowledge: Vue retrieves and stores AuthorizationToken information returned by the server and adds token to each request

Because the background uses token of jwt to verify the identity authority, and the background adds token to the response header after logging in, the foreground needs to store this token and add token to the request header of each request, so that the server can obtain token for identity authentication.

The foreground uses the vue project:

loging. vue (login component)


{
 submitForm(formName) {
 this.$axios
  .post('/api/admin/login', {
  userName: this.ruleForm.userName,
  password: this.ruleForm.password
  })
  .then(successResponse => {
  this.responseResult = JSON.stringify(successResponse.data)
  this.msg = JSON.stringify(successResponse.data.msg)
  if (successResponse.data.code === 200) {
  this.msg='';
  localStorage.setItem('userName',this.ruleForm.userName);
  // Object returned by the server AuthorizationToken Information 
  var authorization=successResponse.headers['authorization'];
  localStorage.setItem('authorization',authorization);
  // Login Successful Jump Page 
  this.$router.push('/dashboard');
  
  }
  })
  .catch(failResponse => {})
 }
 }

main. js (Global Configuration js):


// Automatic giving 1 A vue Add a request header to all requests for the project 
axios.interceptors.request.use(function (config) {
 let token = localStorage.getItem('authorization');
 if (token) {
 config.headers['Authorization'] = token;
 }
 return config;
})

Here, we also need to consider the expiration of token, and bloggers will write another blog to supplement it later.


Related articles: