Pass bearer token with header interceptor (Angular)

We are using Auth0 on an ap that has a .NET Core backend and an Angular front end. Our API checks the bearer token and performs validation that the user is who they say they are. So what that means is I need to pass the bearer token on the front end API requests to the API endpoints. I would like to do this with an interceptor. That way, the token goes with every request because every request needs to be verified in the API. I cannot seem to locate documentation on how to implement this properly with Auth0 and Angular. Could someone please point me in the right direction?

This is a pretty Angular specific question, not so much Auth0 specific. Which Angular version are you using? Did you look at:

I understand. It is quasi-Angular specific. What I mean is I can add header interceptors easily enough, but the issue I am having with Auth0 is that my interceptors are set up to use Observables and it appears that Auth0 utilizes Promises. I don’t mind using Promises, but since our app already utilizes Observables, I would have to do something like

import ‘rxjs/add/observable/fromPromise’;

Which seems somewhat ‘hacky’.

I am using Angular 7 by the way.

I will read through the links you shared, but if you have further thoughts, let me know. Thanks!

Ok…I have decided to implement the usage of storage so I don’t have to make the Auth0 token call with every request. Here is my follow up though. I am following the quick start for Angular and when I run this code…

async login () {
await this.auth0Client.loginWithRedirect( { } );

}

I get this error…

error TS2345: Argument of type '{}' is not assignable to parameter of type 'RedirectLoginOptions'.

Property ‘redirect_uri’ is missing in type ‘{}’ but required in type ‘RedirectLoginOptions’.

I am not certain why I am receiving this.

I have also tried going the route guard method and running this in a CanActivate…

client.loginWithRedirect({
    redirect_uri: 'string',
    appState: { target: state.url }
  });

Basically, I am checking if the user is authenticate. If the boolean returns false, I want to redirect to the Auth0 login.

I’m trying a very similar thing. For the most part, I’ve followed the suggested tutorial for Angular. Much of the setup is in the header files per that tutorial.

I’ve logins working, and when I interpolate this.auth0Client in my header HTML, I see the token I need to add as bearer header in my interceptor. The problem I am having now is accessing that data in my interceptor.

Even during the setting up stages, I was thinking to myself ‘why is this not in a service I can access all around?’ And yeah, now I am wondering this double so, since doing it that way would have had me on my merry way first thing in the morning. Any insight into why do this work in a component instead of a service is appreciated. And ultimately, how do I now get the auth0Client and the token in it to my interceptor.

Reading a bit more on the subject, perhaps it’s as you say President - use some sort of storage like cookie or browser. Access that from the interceptor. Thought I read somewhere not to store tokens, so I’m experiencing a bit of a dissonance. :crazy_face:

Eclectic…I had the same thoughts. I am ok with storing it in storage, since storage is domain dependent. Although not my preference. I am working through this now. I have built an interceptor and am trying to handle my logic there. If I am successful, I will post my results.

Will post my results as well. Right now having trouble getting to that id_token. The JSON structure on this.auth0Client has weird property names I need to drill down through to get to it, including going through cache.cache… so this seems like maybe it’s not where I should be fetching the tokens in the first place…

I think the answer was right under my nose. In starting a post to Stackoverflow, I went to find the Auth0 Angular sample to provide as the code base. In doing so, I stumbled upon its sibling directory: https://github.com/auth0-samples/auth0-angular-samples/blob/master/02-Calling-an-API/src/app/services/api.service.ts

Out of time to comb through it now, but maybe it’ll help someone in the meanwhile.

1 Like

Here is what I did. Seems to work. I am still testing…

If anyone sees something incorrect, please let me know.

@Injectable()
export class AuthenticationInterceptorService implements HttpInterceptor {
  // Variable to hold Auth0 client
  private auth0Client: Auth0Client;
  // Variable to hold local userToken
  private userToken = this.storage.getItemAsString( 'userToken' );

  public constructor(
    private authService: AuthService,
    private storage: StorageAdapterService
  ) { }

  public intercept ( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
    // Get Auth0 scaffolded
    this.getAuth0Token();
    // If userToken exists, clone the http request and add the userToken as the Bearer token
    // Otherwise grab the token from Auth0
    if ( this.userToken ) {
      const tokenReq: HttpRequest<any> = req.clone( {
        setHeaders: {
          Authorization: `Bearer ${ this.userToken }`
        }
      } );
      return next.handle( tokenReq );
    }
    // catch any errors. Ensure user is logged out if necessary and have them log in
    return next.handle( req ).do( ( event: HttpEvent<any> ) => { } )
      .catch( ( err: any ) => {
        console.log( err );
        if ( err instanceof HttpErrorResponse && err.status === 401 ) {
          this.logout();
          this.login();
          return Observable.of();
        }
      } );
  }

  /**
   * Logs the user out of the applicaion, as well as on Auth0
   */
  private logout () {
    this.auth0Client.logout( {
      client_id: this.authService.config.client_id,
      returnTo: window.location.origin
    } );
  }

  /**
   * Logs in the user by redirecting to Auth0 for authentication
   */
  async login () {
    this.auth0Client = await this.authService.getAuth0Client();
    await this.auth0Client.loginWithRedirect( { redirect_uri: 'string' } );
  }
  /**
   * Gets the Auth0Client
   * Pulls the token from the Auth0 client
   * Calls function to set the token in local storage
   * Calls function to pull local storage token and sets it in userToken
   */
  async getAuth0Token () {
    this.auth0Client = await this.authService.getAuth0Client();
    const token = await this.auth0Client.getTokenSilently();
    await this.storeToken( token );
    await this.getToken();
  }
  /**
   * Sets the token in local storage
   */
  async storeToken ( token: string ) {
    await this.storage.setItem( 'userToken', token );
  }
  /**
   * pulls local storage token and sets it in userToken
   */
  async getToken () {
    this.userToken = await this.storage.getItemAsString( 'userToken' );
  }

}

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.