Skip to content

Instantly share code, notes, and snippets.

@donaldpipowitch
Created August 21, 2019 07:59
Show Gist options
  • Save donaldpipowitch/c71055bc77ab17f65eaf90b04d36e433 to your computer and use it in GitHub Desktop.
Save donaldpipowitch/c71055bc77ab17f65eaf90b04d36e433 to your computer and use it in GitHub Desktop.
Try to refresh token once on 401 with RxJS and Angular Http Interceptor
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpErrorResponse,
HttpClient
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { flatMap, catchError } from 'rxjs/operators';
import { tokenUrl } from './config';
@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
constructor(private http: HttpClient) {}
// for every 401 we try to refresh tokens once
intercept(
req: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
return next.handle(req).pipe(
catchError((err) => {
if (
err instanceof HttpErrorResponse &&
err.status === 401 &&
err.url !== tokenUrl
) {
return this.http.get(tokenUrl).pipe(flatMap(() => next.handle(req)));
} else {
return throwError(err);
}
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment