token expiration automatically refreshes token operation on request

  • 2021-08-16 22:53:28
  • OfStack

1. In the development process, we will all be exposed to token. What is the role of token? The main function is for security. When the user logs in, the server will randomly generate a time-sensitive token. Every request of the user needs to carry token to prove the legitimacy of his request. The server will verify token, and only through verification will the request result be returned.

2. When token fails, the current website 1 will do two treatments, one is to jump to the landing page to let users log in again to get a new token, the other is to automatically request a new token when the request fails, and the second way is used more frequently to keep app in the landing state.

3. Let's move on to the topic. We request axios. No matter what request method is used, the principle of refreshing token is the same.

//Encapsulates a request function of Uniform 1, which is not the point


export default function request(url, options) {
  const token = localStorage.getItem('token');
  const defaultOptions = {
    headers: {
      Authorization: `Bearer ${token}`,
    },
    withCredentials: true,
    url: url,
    baseURL: BASE_URL,
  };
  const newOptions = { ...options, ...defaultOptions };
  return axios.request(newOptions)
    .then(checkStatus)
    .catch(error => console.log(error));
}

//Encapsulates a function to detect the return result, and the background return status code code = = = 1002 indicates that token is invalid


let isRefreshing = true;
function checkStatus(response) {
 if (response && response.code === 1002) {
  //  Refresh token Function of , This requires adding 1 Switches to prevent repeated requests 
  if(isRefreshing){
    refreshTokenRequst()
  }
  isRefreshing = false;
  //  This Promise Function is critical 
   const retryOriginalRequest = new Promise((resolve) => {
        addSubscriber(()=> {
          resolve(request(url, options))
        })
      });
      return retryOriginalRequest;
 }else{
   return response;
 }
}

//Refresh the request function of token


function refreshTokenRequst(){
  let data;
  const refreshToken = localStorage.getItem('refreshToken');
  data:{
    authorization: 'YXBwYXBpczpaSWxhQUVJdsferTeweERmR1praHk=',
    refreshToken,
  }
  axios.request({
    baseURL: BASE_URL,
    url:'/app/renewal',
    method: 'POST',
    data,
  }).then((response)=>{
    localStorage.setItem('refreshToken',response.data.refreshToken);
    localStorage.setItem('token',response.data.token);
    onAccessTokenFetched();
    isRefreshing = true;
  });
}

//Promise Function Set


let subscribers = [];
function onAccessTokenFetched() {
  subscribers.forEach((callback)=>{
    callback();
  })
  subscribers = [];
}

function addSubscriber(callback) {
  subscribers.push(callback)
}

Summary:

In fact, token fails, and token is refreshed automatically, which is easier to handle when there is only one request on the page. However, if there are multiple requests on the page at the same time, and token fails, it needs a little more complicated processing, and the solution is mainly to use Promise function for processing.

Every token invalid request will be stored in an Promise function set. When the refresh token function is executed, these Promise functions will be executed in batches and the request results will be returned.

There is another point to note. 1. Here, set a switch isRefreshing to refresh token, which is very necessary to prevent repeated requests.


Related articles: