I am trying to implement using Angular5 an HttpInterceptor
to inject an Authorization header in all HTTP requests.
I rely on a third party library (ADAL, here called AuthService
) that exposes a acquireToken()
method to get the token to be used for Bearer authorization.
The problem is that aquireToken()
returns an observable, and i have to subscribe to get the real string I need.
Therefore, my code never injects the header, i suppose because next.handle()
is executed before acquireToken()
returns any value.
How can i ensure that the next handler is called only after the token has been retrieved?
import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import {AuthService} from 'mylibrary';
@Injectable()
export class MyInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let headers = req.headers || new HttpHeaders();
this.auth.acquireToken(req.url)
.subscribe((token: string) => {
headers = headers.append('Authorization', 'Bearer ' + token);
});
return next.handle(req.clone({ headers: headers }));
}
}