Before each request a HTTP interceptor checks if the access token is expired and if so, it first renews the token and then continues the request.
The problem is on pages that have multiple requests. On those pages the interceptor tries to renew the token for each request.
How can I share the token renewal request in this case?
The method that is responsible for token renewal is this:
renewToken() {
let refreshToken = // get refresh token
let accessToken = // get access token
if (!refreshToken || !accessToken)
return;
let requestData = {
accessToken: accessToken,
refreshToken: refreshToken
}
return this.http.post<ApplicationToken>(`${this.baseUrl}/renewToken`, requestData)
.pipe(
// I tried share() shareReplay(1) and publishReplay(1) here but no luck
);
}
And this is how the interceptor uses that method:
...
// in case we need to renew the token
return this.accountService.renewToken()
.pipe(
switchMap(t => {
this.accountService.saveToken(t);
token = this.accountService.getAccessToken();
var newReq = this.setToken(req, token);
return next.handle(newReq);
})
);
...
You need to check if refresh token request is in progress or not because you don’t want other calls to come in and call refreshToken again.
Here I've created RefreshTokenInterceptor class for you.
You just need to customize it and follow the comments: