I have used access-token
and refresh-token
mechanism for authentication in API. when my access-token gets expired I am getting 401 Unauthorized
error in APIs. so I am calling request which returns fresh access-token using refresh-token which is working correctly. but issue is what ever code written inside .subscribe
function is not getting re-executed.
getActivePlan() {
this.myPlanExplainerActive = true;
var route = this.router.url;
this.ps.getUserPlan().subscribe(res => { <========== Getting 401 Unauthorized error when accss-token expired
var plans = res.data.plans; <===== After getting new access-token execution never goes inside.
var activeplan = plans.find(i => i.plan.isActive == true);
if (activeplan != undefined) {
this.activePlanId = activeplan.plan.planId;
if (route != "/planparser/new-pdf-upload" && this.activePlanId != '') {
this.router.navigate(['planparser/view-plan/', this.activePlanId]);
}
}
else {
this.router.navigate(['planparser/new-pdf-upload/']);
}
});
}
here when I get 401 Unauthorized error in getUserPlan() API, my interceptor get hits and fetch new access-token. but, execution never goes inside subscribe so further code not getting executed.
intercept(request: HttpRequest<unknown>, next: HttpHandler):
Observable<HttpEvent<unknown>> {
let clonedRequest = request.clone();
if (request.url.indexOf("/auth/oauth/token") == -1) {
const auth = this.inject.get(AuthService);
let cloned;
if (auth.getToken()) {
cloned = request.clone({
setHeaders: {
Authorization: `Bearer ${auth.getToken()}`,
'Accept': 'application/json'
}
});
}
else {
cloned = request.clone();
}
return next.handle(cloned).pipe(
catchError(
(async (error: HttpErrorResponse) => {
if (error.status === 401) {
return this.handle401Error(request, next);
} else {
return throwError(error);
}
})
)
) as any;
}
else if (request.url.indexOf('/auth/oauth/token') != -1) {
clonedRequest = request.clone({
setHeaders: {
Authorization: `Basic ${window.btoa('ClientId' + ':' + 'secret')}`,
'Content-Type': "application/x-www-form-urlencoded"
}
});
}
return next.handle(clonedRequest)
.pipe(
catchError(
((error: HttpErrorResponse) => {
if (error.status !== 401) {
this.msgs.sendMessage({ command: 'Sorry, we are unable to process your plan. Please upload your correct NDIS plan PDF again.' });
}
return throwError(error);
})
)
);
}
private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
if (!this.isRefreshingToken) {
this.isRefreshingToken = true;
this.tokenSubject.next(null);
return this.authService.refreshTokenAPIcall().pipe(
switchMap((token: any) => {
this.isRefreshingToken = false;
this.tokenSubject.next(token.access_token); <============== getting new token
return next.handle(this.addToken(request))
})).subscribe(res => {
console.log(res);
});
} else {
return this.tokenSubject.pipe(
filter(token => token != null),
take(1),
switchMap(jwt => {
return next.handle(this.addToken(request));
}));
}
}