Angular 11 Lazy loaded module, missing token in service request

Hi,

I have an Angular 11 SPA with a lazy loaded module.

I am using “@auth0/auth0-angular”: “^1.3.2”

The lazy loaded module is protected by AuthGuard from “@auth0/auth0-angular”;

I have also added this to my lazy loaded module file to try and get the AuthGuard to add the token.
{provide: HTTP_INTERCEPTORS, useClass: AuthHttpInterceptor, multi: true}

But the token is missing in the lazy loaded module’s service request?

Do you have any suggestions as to a solution.

Thank you
Peter

Waited a few days hoping for an answer or suggestion but sadly no. So here is what I have done for an Angular 11 Lazy Loaded module.

Created a HttpInterceptor for my lazy loaded module that adds the token to the request.

Here is the code if anyone has a similar issue and needs a workaround.

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpResponse, HttpRequest, HttpHandler } from '@angular/common/http';
import { Observable } from 'rxjs';
import {AuthService} from "@auth0/auth0-angular";
import {mergeMap} from "rxjs/operators";

@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {

  constructor(private auth: AuthService) {
  }
  intercept(httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.auth.getAccessTokenSilently().pipe(
      mergeMap(token => {
      // Add token to request
        const tokenReq = httpRequest.clone({
        setHeaders:{ Authorization: `Bearer ${token}`}
      });
      return next.handle(tokenReq);
    }));
  }
}

In my lazy loaded module I needed to have these declarations for the token to be added.

providers: [
  // Auth0 interceptor that is not getting called.
  // Interestingly if you remove this interceptor the token never gets fetched.
  {provide: HTTP_INTERCEPTORS, useClass: AppHttpInterceptor, multi: true},
  // My custom interceptor to add the token.
  {provide: HTTP_INTERCEPTORS, useClass: AuthHttpInterceptor, multi: true},

]

1 Like

I had the same problem for my angular 10 app. I was also able accomplish this the same way using getAccessTokenSilently() for my requests.

1 Like

Thanks for sharing it with the rest of community!