2

I have created a custom authentication interceptor which implements HttpInterceptor. I will be adding headers to the every request I make with httpClient. Now I have few requests which don't need authentication headers to be added.

Below is the code of my custom interceptor for reference

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private franchiserService: FranchiserService,
              private currentMerchantService: CurrentMerchantService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {

    console.log('Request Intercepted');

    const franchiserKey = this.franchiserService.franchiser.apiKey;
    const merchantKey = this.currentMerchantService.merchant.apiKey;

    const authReq = req.clone({
      headers: req.headers.append('franchiserKey', franchiserKey).append('merchantKey', merchantKey),
      url: environment.origin + req.url
    });

    return next.handle(authReq);
  }

}

How I can implement custom interceptor which can do the both?

1 Answers1

1

You can by-pass global auth headers in Angular by adding your own http handler type (check handler types in angular documentation here https://angular.io/api/common/http/HttpHandler) in the services that do not need to be intercepted

import { HttpClient, HttpBackend } from @angular/common/http;

 constructor(private http: HttpClient, private handler: httpBackend ) {
     this.http = new HttpClient(handler); // provide handler of type HttpBackend   }

Adding this handler of type HttpBackend will tell it to by pass all other handlers and move to the last one. Auth interception in angular usually happens in the order auth interceptors were added, finally ending at the HttpBackend. Adding it directly like this skips all interception

Officialzessu
  • 897
  • 7
  • 6
  • This does work! But I'm not sure if instanciating HttpClient is the right thing to do here. I think a better way would be following this answer: https://stackoverflow.com/a/53679340/1707589 – fasfsfgs Jan 10 '19 at 18:12