Realize Vue with the interceptor of axios Thinking of login status verification in JS

When performing login verification in Vue, the idea should be as follows: first determine whether a routing page needs to be logged in to access. If so, the user needs to log in. If not, the user can access it directly.

Well, first of all, in the background system, not every page needs login permission, so we need to mark the routing page that needs to be verified through the meta tag of the route. When configuring the route, we can add the field whether to login in the meta attribute. If requireAuth is true, it means that this route needs to be logged in to access:

{
  path: '/userInfo',
  name: 'userInfo',
  meta: {
    requireAuth: true,  // This routing item requires permission verification
  }
  component: userInfo
}, {
  path: '/userList',
  name: 'userList',    // This routing item does not require permission verification    
  component: userInfo
}

After that, we can define a route guard. Each time the route jumps, we will perform a permission verification. Refer to the following code

router.beforeEach((to, from, next) => {
  if(to.meta.requireAuth) { // If the routing item requires permission verification
    /* 
      Take out the token code from Vuex to indicate that you have logged in
     (The token of the front end can be forged, so it is not completely reliable. Continue later)
    */
    if (store.state.token) { 
      next() // Normal jump page
    } else {
      next({
        path: '/login',
        query: {redirect: to.fullPath}  
        /* Take the jump route address as a parameter to the landing page, and jump back to the page after successful login */
      })
    }
  } else { // If permission verification is not required, you can directly enter the routing page
      next();
  }
})

If the login status (token) in the user's Vuex exists, it means login. If there is no value, jump to the login page. After logging in on the login page, the user should save the login status (token) in Vuex. (in fact, for persistent storage, the login status should also be stored in localStorage or cookie)

However, this is not reliable. Firstly, the token can be forged by the user. Secondly, it is possible that the token exists in the front end. However, due to the long login time, it has exceeded the maximum login validity period. At this time, the token in the back end has become invalid.

Therefore, the permission verification is not accurate. Next, we can further ensure the accuracy of permission status through the back-end layer verification when sending a request.

In this step, the interceptor in axios is used, so the following code is based on the project using axios. Interceptors of axios, default configuration (axios.defaults) and axios The instance created by create () is actually very useful when encapsulating requests. If you haven't touched it, go to the official document and have a look!

Let's start by intercepting each request as follows. This means that if the front end has a token, I will give the token to the back end every time. After the back end gets the token, it will go to the back end for another permission verification, and then feed back the verification results in the interface:

axios.interceptors.request.use( requestConfig => {
  if (store.state.token) {
    config.headers.Authorization = `${store.state.token}`;
  }
  return requestConfig;
}, err => {
  return Promise.reject(err);
});

Then let's look again. We must write another response interceptor to process the response data. If the back-end gets the token from the front-end and finds that the token is invalid, we require the back-end interface to return the return code of 401, so that the front-end can handle it as follows:

axios.interceptors.response.use( response => {
    return response;
  }, error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:  
          /* 
            Returning 401 indicates that the token of the front end has expired
            Of course, you can also define other ways with the backend to indicate token failure
            The front end needs to clear the token in Vuex, and the page jumps to the login page
          */ 
          store.commit(types.LOGOUT);
          router.replace({
            path: 'login',
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
      }
    }
    return Promise.reject(error.response.data) //Returns the error information returned by the interface
});

With the help of axios interceptor, we not only do the login verification at the front end, but also carry the data to the back end for login verification again every time we request the back-end interface. Such a login verification process is very standard.

Keywords: axios Vue

Added by jwb666 on Tue, 18 Jan 2022 12:03:42 +0200