So I want to renew access token if the token is expired using refresh token and this is what my token interceptor looks like:
intercept(req: HttpRequest<any>, next: HttpHandler) {
let authservice = this.injector.get(AuthService)
let tokenreq = req.clone({
setHeaders: {
Authorization: `Bearer ${authservice.setToken()}`
}
})
return next.handle(tokenreq).pipe(
catchError((error) => {
if (error.error.message == 'The incoming token has expired') {
authservice.renewToken()
let tokenreq = req.clone({
setHeaders: {
Authorization: `Bearer ${authservice.setToken()}`
}
})
return next.handle(tokenreq)
}
else return throwError(error)
})
);
}
}
The problem is after I get the expired token message the authservice.renewToken()
and authservice.setToken() were called at the same time so the expired token was set again.
Another problem is if the user opens the application again with the expired token in cookies all the GET method will throw an error and will request for new token multiple times. How can I handle expire token error?