Refreshing AWS Access Token with Amplify and Axios

Authentication is one of those foundational pieces of your application that can be complex if your requirements don’t fit some predetermined mold. For that reason, I am aiming to provide you a quick and easy way to refresh an AWS access token via the Amplify and Axios libraries.

This example is just one of many ways to accomplish the given task, but for this use case and time of writing Amplify does not support refreshing the access token automatically when using a custom authentication provider. That means it’s up to the engineer to fit the refresh logic somewhere into their application landscape.

Using axios’s interceptors, you can intercept outgoing requests and introduce functionality prior to the original request going out. Here, we make a call to Amplify’s
Auth module to grab the currentSession. Inside currentSession, Amplify hits its own internal cache and will return the token if it hasn’t expired, otherwise it will
make its own request to AWS and refresh the access code. Now, we are free to utilize the current or refreshed access code and add it to the original outgoing request.

export const axiosRequestInterceptor = async config => {
const session = await Auth.currentSession();
 
const token = delve(session, 'idToken.jwtToken');
  if (token) {
    config.headers.Authorization = token;
  }
  return config;
};
axios.interceptors.request.use(axiosRequestInterceptor, e => Promise.reject(e));
Leave a Reply

Your email address will not be published. Required fields are marked *

*

*