Angular 8 Intercept call to refresh token
@AntGrisha , thanks for posting the solution after correcting.Saved me lots of work. I have added error handling as well.Might help some beginner like me and so posting it here.I have used angular 9.1.5 version.
Should pipe in the request handler as below.
return next.handle(this.injectToken(req)).pipe(
catchError(this.handleError)
Error handler function definition
injectToken(request: HttpRequest<any>) {
const token = this.authService.getToken(AuthService.TOKEN_NAME);
return request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
}
//Error handling function
handleError(error: HttpErrorResponse){
console.log('Error Occurred: '+error);
if(error.status==401){
return throwError("Unauthorized!");
}
else{
return throwError(error);
}
I've excluded refresh request from interceptor scope and now it's working. I've made a temporary fix in order to see it's working in the fastest way.
Now my TokenInterceptor looks like:
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { AuthService } from './auth.service';
import { Observable, BehaviorSubject, Subject } from 'rxjs';
import { switchMap, take, filter } from 'rxjs/operators';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
private refreshTokenInProgress = false;
private refreshTokenSubject: Subject<any> = new BehaviorSubject<any>(null);
constructor(public authService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (request.url.indexOf('refresh') !== -1) {
return next.handle(request);
}
const accessExpired = this.authService.isAccessTokenExpired();
const refreshExpired = this.authService.isRefreshTokenExpired();
if (accessExpired && refreshExpired) {
return next.handle(request);
}
if (accessExpired && !refreshExpired) {
if (!this.refreshTokenInProgress) {
this.refreshTokenInProgress = true;
this.refreshTokenSubject.next(null);
return this.authService.requestAccessToken().pipe(
switchMap((authResponse) => {
this.authService.saveToken(AuthService.TOKEN_NAME, authResponse.accessToken);
this.authService.saveToken(AuthService.REFRESH_TOKEN_NAME, authResponse.refreshToken);
this.refreshTokenInProgress = false;
this.refreshTokenSubject.next(authResponse.refreshToken);
return next.handle(this.injectToken(request));
}),
);
} else {
return this.refreshTokenSubject.pipe(
filter(result => result !== null),
take(1),
switchMap((res) => {
return next.handle(this.injectToken(request))
})
);
}
}
if (!accessExpired) {
return next.handle(this.injectToken(request));
}
}
injectToken(request: HttpRequest<any>) {
const token = this.authService.getToken(AuthService.TOKEN_NAME);
return request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
}
}
Thanks to @JBNizet