Darran Edwards
Darran Edwards

Reputation: 11

Add Auth0 bearer token to Angular HttpInterceptor

I am writing an HttpInterceptor that will add a bearer token to an outgoing request. The bearer token to be obtained by calling method getAccessTokenSilently. Method is part of Auth0 service and makes an http call to authorizer for token if not cached locally.

    getAccessTokenSilently(options?: GetTokenSilentlyOptions): Observable<string>;

Basically my code has to do the following;

    import { AuthService } from '@auth0/auth0-angular';
    
    @Injectable()
    export class AuthHttpInterceptor implements HttpInterceptor {
      constructor(public auth:AuthService) {}

      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const token = this.auth.getAccessTokenSilently();
        return next.handle(req.clone({ setHeaders: { token } }));
      }
    }

To get the token I need to subscribe to observer for getAccessTokenSilently but by the time the token is available, the method has already exited.

I tried using await function but it does not work because getAccessTokenSilently does not return a promise.

How do I pause my function while I wait for token to be available?

Upvotes: 1

Views: 929

Answers (1)

El-Mo
El-Mo

Reputation: 380

'Pausing' the main thread of a web application is, and will always be, a terrible idea. Luckily you won't have to do that in this case, because you can use rxjs to achieve what you want to do. Something similar to the following should do the trick:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.auth.getAccessTokenSilently()
        .pipe(
            mergeMap((token) => {
                return next.handle(req.clone({ setHeaders: { token } }));
            })
        );
}

If you're planning to do more work with observables, you should definitely checkout rxjs and do a couple of tutorials.

Upvotes: 2

Related Questions