0

What is the correct way to request a new JWT authentication token via refresh tokens within AngularJS?

I already have an implementation that, on every API request, checks whether the session needs refreshing and, if so, requests a new token from the webserver. But, if a page makes 3 calls at once it requests a new refresh token for each call which seems incorrect - I would think it should only update the token once.

Is there a way to block other calls or should I put the refresh on an interval and not do it via interceptors?

Interceptor request method

request = (config: angular.IRequestConfig) => {

    this.setBearerToken(config);

    var responsePromise = this.$q.when(config);

    if (config.url !== this.tokenUrl) {

        const factSession = this.$injector.get("factSession") as Session;

        if (factSession.shouldRefreshToken()) {
            responsePromise = factSession
                .refreshSession()
                .then(() => {
                    this.setBearerToken(config);

                    return config;
                });
        }
    }

    return responsePromise;
}
Chris
  • 26,744
  • 48
  • 193
  • 345

1 Answers1

1

Just enhance your refreshSession method, so it wont refresh several times.

var refreshPromise;

refreshSession: () => {
  if (!refreshPromise) {
    refreshPromise = $http.get(...);
    refreshPromise.finally(() => refreshPromise = null);
  }

  return refreshPromise;
}
Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38