title: angular 9 intercept XHR requests to add Bearer token
body: <p>I want to intercept ALL xhr requests to add authentication in my Angular app, for this I add an HttpInterceptor but it's not fired for XHR requests, any idea how I can intercept these requests ??</p>
  
  <p>Thank you.</p>
  
  <p><strong><em>auth.interceptor.ts</em></strong></p>
  
  <pre><code>import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
  import { Observable, from } from 'rxjs';
  import { OktaAuthService } from '@okta/okta-angular';
  import { Injectable } from '@angular/core';
  
  @Injectable()
  export class AuthInterceptor implements HttpInterceptor {
  
    constructor(private oktaAuth: OktaAuthService) {
    }
  
    intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
      return from(this.handleAccess(request, next));
    }
  
    private async handleAccess(request: HttpRequest&lt;any&gt;, next: HttpHandler): Promise&lt;HttpEvent&lt;any&gt;&gt; {
      // Only add an access token to whitelisted origins
      const allowedOrigins = ['http://localhost'];
      console.log('Intercept HTTP request to adding Bearer token');
      if (allowedOrigins.some(url =&gt; request.urlWithParams.includes(url))) {
        const accessToken = await this.oktaAuth.getAccessToken();
        if (accessToken) {
          request = request.clone({
            setHeaders: {
              Authorization: 'Bearer ' + accessToken
            }
          });
        } else {
          //No token; proceed request without bearer token
          console.log('No token added to HTTP request');
          return next.handle(request).toPromise();
        }
      }
      return next.handle(request).toPromise();
    }
  }
  </code></pre>