1 year ago
#166203
incognita
How to fix interceptor?
My interceptor work good for add access token to header and refresh tokens. But if i brake my access and refresh token i my refresh token failed two times. What behavior i need is when refresh token request failed in first time then i want to clear storage and redirect user to login. But in this case my catchError inside authService.pipe works only on with second failed refresh token request
export class AuthInterceptor implements HttpInterceptor {
private isRefreshing = false;
private refreshTokenSubject = new BehaviorSubject<string | null>(null);
constructor(private storageService: StorageService, private authService: AuthService, private router: Router) {
}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
let authReq = request;
const token = this.storageService.getToken();
if (token !== null) {
authReq = this.addTokenHeader(request, token);
}
return next.handle(authReq).pipe(
catchError(error => {
if (error instanceof HttpErrorResponse && error.status === 401) {
return this.handle401Error(authReq, next);
}
return throwError(error);
})
);
}
private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
if (!this.isRefreshing) {
this.isRefreshing = true;
this.refreshTokenSubject.next(null);
const token = this.storageService.getRefreshToken();
if (token) {
return this.authService.refreshToken(token).pipe(
switchMap((token: TokenModel) => {
this.isRefreshing = false;
this.storageService.setToken(token.accessToken);
this.storageService.setRefreshToken(token.refreshToken);
this.refreshTokenSubject.next(token.accessToken);
return next.handle(this.addTokenHeader(request, token.accessToken));
}),
catchError((error) => {
this.isRefreshing = false;
this.storageService.clearStorage();
this.router.navigate([''])
return throwError(error);
}),
);
}
}
return next.handle(request)
}
addTokenHeader(request: HttpRequest<any>, token: string) {
return request.clone({headers: request.headers.set('Authorization', 'Bearer ' + token)});
}
}
Please help my find what i am doing wrong and how can i fix it
angular
jwt
angular-http-interceptors
refresh-token
0 Answers
Your Answer