import { Injectable } from '@angular/core' ; import { HttpEvent , HttpInterceptor , HttpHandler , HttpRequest } from '@angular/common/http' ; import { Observable } from 'rxjs' ; import { mergeMap } from 'rxjs/operators' ; import { AdalService } from './adal.service' ; @ Injectable ( ) export class AdalInterceptor implements HttpInterceptor { constructor ( private adal ) { } intercept ( request , next ) { const resource = this . adal . getResourceForEndpoint ( request . url ) ; const skipAdal = request . headers . get ( 'skip-adal' ) ; if ( ! resource || skipAdal ) { return next . handle ( request ) ; } if ( ! this . adal . userInfo . authenticated ) { throw new Error ( 'Cannot send request to registered endpoint if the user is not authenticated.' ) ; } return this . adal . acquireToken ( resource ) . pipe ( mergeMap ( ( token ) => { const authorizedRequest = request . clone ( { headers : request . headers . set ( 'Authorization' , 'Bearer ' + token ) , } ) ; return next . handle ( authorizedRequest ) ; } ) ) ; } }