Skip to content
Advertisement

Acquiring a new token with `axios.interceptors`

When the token expires, I want to get a new token based on refresh_token. I have read that this can be obtained with axios.interceptors.

Please check if:

  • Have I correctly configured axios.interceptors?
  • Have I placed it in the right place, i.e. above theItems class.
  • axios.interceptors.response is assigned to theinterceptor variable. What should I do with this variable?

In addition to `axios.interceptors’, I need to get a new token. The token is valid for 24 hours.

  • Do I have to wait 24 hours to test whether it works, or is it possible in a different way, faster?
  • Where should I put ‘client_id’, ‘secret_id’, ‘grant_type’?

Code here: https://stackblitz.com/edit/react-pkea41

import axios from 'axios';

axios.defaults.baseURL = localStorage.getItem('domain');

const interceptor = axios.interceptors.response.use(
  response => response,
  error => {
      // Reject promise if usual error
      if (errorResponse.status !== 401) {
          return Promise.reject(error);
      }

      /* 
       * When response code is 401, try to refresh the token.
       * Eject the interceptor so it doesn't loop in case
       * token refresh causes the 401 response
       */
      axios.interceptors.response.eject(interceptor);

      return axios.post('/api/refresh_token', {
          'refresh_token': JSON.parse(localStorage.getItem('token'))['refresh_token']
      }).then(response => {
          /*saveToken();*/
          localStorage.setItem('token', JSON.stringify(response.data));
          error.response.config.headers['Authorization'] = 'Bearer ' + response.data.access_token;
          return axios(error.response.config);
      }).catch(error => {
          /*destroyToken();*/
          localStorage.setItem('token', '');
          this.router.push('/login');
          return Promise.reject(error);
      }).finally(createAxiosResponseInterceptor);
  }
);

class Items extends Component {

  constructor (props) {
    super(props);
    this.state = {

    }
  }


  render () {
    return (
      <div >

      </div>
    )
  }
}


render(<Items />, document.getElementById('root'));

Advertisement

Answer

Please check if I have correctly configured axios.interceptors.

I think it works. But I suggest that you should test it carefully.This is a good article to refer https://blog.liplex.de/axios-interceptor-to-refresh-jwt-token-after-expiration/

Have I placed it in the right place, i.e. above theItems class. ?

You should create a service function to wrap Axios and API configs,and interceptor of course

axios.interceptors.response is assigned to the interceptor variable. What should I do with this variable?

It is just a variable used to define the interceptor. Don’t care about it. If you want to avoid assigning it, just do it inside a function like this Automating access token refreshing via interceptors in axios

I have to wait 24 hours to test whether it works, or is it possible in a different way, faster?

You can change the token saved in your localStorage, and do that

Where should I put ‘client_id’, ‘secret_id’, ‘grant_type’?

If you store it inside localStorage, it’s accessible by any script inside your page (which is as bad as it sounds as an XSS attack can let an external attacker get access to the token).

Don’t store it in local storage (or session storage). If any of the 3rd part scripts you include in your page gets compromised, it can access all your users’ tokens.

The JWT needs to be stored inside an HttpOnly cookie, a special kind of cookie that’s only sent in HTTP requests to the server, and it’s never accessible (both for reading or writing) from JavaScript running in the browser.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement