0

Refrence : https://gist.github.com/tobbbe/08e01db92c32346b226333a3f952df22

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
           return next.handle(this.addToken(request))
          .pipe(
          catchError((error, ca) => {
            if (error instanceof HttpErrorResponse) {
              switch ((<HttpErrorResponse>error).status) {
                case 401:
                  return this.handle401Error(request, next)
                default:
                  return ErrorObservable.create(error);
              }
            } else {
              return ErrorObservable.create(error);
            }
          })
          )
      }

// 401 Error method

  handle401Error(req: HttpRequest<any>, next: HttpHandler) {
        if (this.isRefreshingToken) {
            this.isRefreshingToken = false;

            // Reset here so that the following requests wait until the token
            // comes back from the refreshToken call.
            this.tokenSubject.next(null);
            const http = this.inj.get(HttpClient);

    let customReq: any;   
    let client_secret= 'temp';
    let basicheader = btoa(client_secret);

       return http.get(AppUtils.REFRESH_TOKEN + localStorage.getItem(AppUtils.STORAGE_ACCOUNT_REFRESH_TOKEN), { new HttpHeaders().set('Authorization', 'Basic ' + basicheader)})  // line 38
              .pipe(
                  switchMap((token: any) => {
                    console.log("token " +JSON.stringify(token));
                    if (token) {
                        localStorage.setItem(AppUtils.STORAGE_TOKEN, token["access_token"]);
                        this.tokenSubject.next(token["access_token"]);
                        return next.handle(this.addToken(req));
                    }

                    console.log("refresh failed");
                    // If we don't get a new token, we are in trouble so logout.
                     this.logoutUser();
                      return EmptyObservable.create();

                }, err => {
                    console.log("error calling add category" + JSON.stringify(err));
                   return EmptyObservable.create();
              }),
                catchError(error => {
                    console.log("error  2" +error);
                    // If there is an exception calling 'refreshToken', bad news so logout.
                     this.logoutUser();
                      return EmptyObservable.create();
                }),
                finalize(() => {
                    this.isRefreshingToken = true;
                })
                )
        } else {
                return this.tokenSubject
                .filter(token => token != null)
                .take(1)
                .switchMap(token => {
                    return next.handle(this.addToken(req));
                });


        }

    }

The code is to implement the refresh token, reference https://www.intertech.com/Blog/angular-4-tutorial-handling-refresh-token-with-new-httpinterceptor/

Having issue like when the line 38 refresh call is made and it returns success then the use case works fine. On 401 error response i.e error response, control is not going to catError or error block as expected. On debug mode cant figure out where the control goes after failure.

What is going wrong with this implementation, how can I make the control to be in error block after 401 error response. Using angular 5 here.

added request interceptor complete code in this https://plnkr.co/edit/7ASmr... not the working version added just the code.

user630209
  • 1,123
  • 4
  • 42
  • 93

1 Answers1

0

I have written the following interceptor in order to handle HttpErrorResponse, in my case: 401 and 403 status code:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

import {AuthService} from '../Services/AuthService';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private auth: AuthService) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

      return next.handle(req).do((event: HttpEvent<any>)  => {},
      (err: any) => {

        if (err instanceof HttpErrorResponse) {

          if (err.status === 401 || err.status == 403) {
            // Rest of your code
          }
        }
      });
    }
}

And added to the providers in the @NgModule (app.module.ts):

providers: [
     // Rest of the providers
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
]

Note that the do() operator is used to handle the error response (HttpErrorResponse) and you have to import it as well.

import 'rxjs/add/operator/do';
AhmadReza Payan
  • 2,171
  • 1
  • 23
  • 33