5

I have an app that has OAuth2 implemented. It works fine, but I'm confused with refresh_tokens here. My app is using React + Redux combination.

I know I need to check if my access_token expired and then ask for new one using refresh_token. Okay... But when should I refresh it? After the 401 happened or in time when some API request that needs authorization is ready (just before send)?

I also know how to use HTTP interceptors to get all API requests before send or detect the 401 responses. The problem is I'm confused how to solve the problem in Redux flow. How to "freeze" a request for the time the token is being refreshed? Or how to repeat the request when I solve the problem on 401 response?

Nickon
  • 8,180
  • 10
  • 52
  • 105

1 Answers1

7

When first authenticating with server successfully, we will have {access_token, expires_in, refresh_token}. We will store access_token and expires_in in session storage and refresh_token in local storage.

Whenever getting access_token for fetching data (you should enhance/wrap the fetch with filling access_token), you'll check if the expires_in is due soon (less than 1 minute, or what you feel comfortable), then we use the refresh_token to request new access_token. And of course, we have to update new result to the storage as well.

Pseudo code:

function getToken() {
    const expiresIn = storage.getItem(KEY_EXPIRES_IN);
    const accessToken = storage.getItem(KEY_ACCESS_TOKEN);
    if (accessToken
        && (!expiresIn || moment.unix(Number(expiresIn)).diff(moment(),   'minute') > 1)) {
        return accessToken;
    }
    return refreshToken();
}

Above function will be called every time you make a request to server.

P/S: you may want to make it as promise to use with isomorphic-fetch

Community
  • 1
  • 1
idealweek.net
  • 306
  • 2
  • 8