I am trying to achieve the following in my HTTP calls
- If an API request returns 401 then call the refresh token endpoint to get the token.
- Retry the same HTTP call with the updated token
Here is the relevant code
// this method invoke when the HTTP interceptor returns 401 status code
handle401(request: HttpRequest<any>, next: HttpHandler) {
if (!this.refreshTokenInProgress) {
this.refreshTokenInProgress = true;
this.refreshTokenSubject.next(null);
return this.getToken((data: any) => {
this.refreshTokenInProgress = false;
this.refreshTokenSubject.next(data);
request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${data}`) });
return next.handle(request);
})
} else {
return this.refreshTokenSubject.pipe(
filter(token => token != null),
take(1),
switchMap((accessToken) => {
request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${accessToken}`) });
return next.handle(request);
})
);
}
}
Obtain the refresh token
getToken(cb: any) {
let poolData = {
UserPoolId: environment.cognitoUserPoolId, // Your user pool id here
ClientId: environment.cognitoAppClientId // Your client id here
};
let userPool = new CognitoUserPool(poolData);
let cognitoUser = userPool.getCurrentUser();
cognitoUser?.getSession((err: any, session: any) => {
const refresh_token = session.getRefreshToken();
cognitoUser?.refreshSession(refresh_token, (refErr, refSession) => {
const userToken = localStorage.getItem('token');
cb(userToken);
});
})
}
While executing I am getting the new token from the getToken
method, but the retry of the same HTTP call is not happening.
The execution of HTTP request stops after obtaining the refresh token from the getToken
method.
Can somebody please help on this issue