Search code examples
reactjsreact-nativereact-reduxjwtredux-saga

Getting access token with the refresh token after expiration(JWT)


I get 401 error after a while when the page is reloaded, I figured it could be because the access token is expired. How do I set a new token with my refresh token? The below function runs every time the user visits a new page or refreshes the page. But it doesn't seem to work.

export async function currentAccount() {


  if (store.get('refreshToken')) {
    const query = {
      grant_type: 'refresh_token',
      companyId: store.get('lastCompanyId'),
      refresh_token: store.get('refreshToken'),
    }
    const queryString = new URLSearchParams(query).toString()
    const actionUrl = `${REACT_APP_SERVER_URL}/login?${queryString}`
    return apiClient
      .post(actionUrl, { auth: 'basic' })
      .then(async response => {
        if (response) {
          const { access_token: accessToken } = response.data
            store.set('accessToken', accessToken)
          return response.data
        }
        return false
      })
      .catch(err => {
        console.log('error', err)
        store.clearAll()
      })
  }
  return false
}

Login sets the access tokens

export async function login(email, password) {
  const query = {
    grant_type: 'password',
    username: email,
    password,
  }
  const queryString = new URLSearchParams(query).toString()
  const actionUrl = `${REACT_APP_SERVER_URL}/login?${queryString}`
  return apiClient
    .post(actionUrl, { auth: 'basic' })
    .then(async response => {
      if (response) {
        const {
          data: {
            access_token: accessToken,
            refresh_token: refreshToken,
          },
        } = response
        const decoded = jsonwebtoken.decode(accessToken)
        response.data.authUser = decoded.authUser
        const { userId, profileId, companyId } = decoded.authUser
        if (accessToken) {
          store.set('accessToken', accessToken)
          store.set('refreshToken', refreshToken)
        }
        return response.data
      }
      return false
    })
    .catch(err => console.log(err))
}

saga users.js

export function* LOAD_CURRENT_ACCOUNT() {
  yield put({
    type: 'user/SET_STATE',
    payload: {
      loading: true,
    },
  })
  const { authProvider } = yield select((state) => state.settings)
  const response = yield call(mapAuthProviders[authProvider].currentAccount)
  if (response) {
    const decoded = jsonwebtoken.decode(response.access_token)
    response.authUser = decoded.authUser
    yield store.set('id', id)
    try {
      const user = yield call(LoadUserProfile)
      if (user) {
        const { company } = user
        yield put({
          type: 'user/SET_STATE',
          payload: {
            ...user,
            preferredDateFormat: user.preferredDateFormat || 'DD/MM/YYYY',
            userId,
            id,
          },
        })
      }
    } catch (error) {
    }
  }else{
    store.set('refreshToken', response.refreshToken)
  }

  yield put({
    type: 'user/SET_STATE',
    payload: {
      loading: false,
    },
  })
}

Solution

  • You can get a new access token with your refresh token using interceptors. Intercept and check for response status code 401, and get a new access token with your refresh token and add the new access token to the header.

    Example:

    return apiClient
      .post(actionUrl, { auth: 'basic' })
      .then(async response => {
        if (response) { // check for the status code 401 and make call with refresh token to get new access token and set in the auth header
          const { access_token: accessToken } = response.data
            store.set('accessToken', accessToken)
          return response.data
        }
        return false
      });
    

    Simple Interceptor example,

    axios.interceptors.request.use(req => {
      req.headers.authorization = 'token';
      return req;
    });
    

    Interceptor example for 401

    axios.interceptors.response.use(response => response, error => {
    
        if (error.response.status === 401) {
           // Fetch new access token with your refresh token
           // set the auth header with the new access token fetched
        }
     });
    

    There are several good posts on Interceptors usage for getting a new access token with your refresh token

    https://thedutchlab.com/blog/using-axios-interceptors-for-refreshing-your-api-token

    https://medium.com/swlh/handling-access-and-refresh-tokens-using-axios-interceptors-3970b601a5da

    Automating access token refreshing via interceptors in axios

    https://stackoverflow.com/a/52737325/8370370