forked from benbaran/adal-angular4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadal.interceptor.ts
38 lines (31 loc) · 1.4 KB
/
adal.interceptor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } 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: AdalService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// if the endpoint is not registered then pass
// the request as it is to the next handler
const resource = this.adal.GetResourceForEndpoint(req.url);
if (!resource) {
return next.handle(req.clone());
}
// if the user is not authenticated then drop the request
if (!this.adal.userInfo.authenticated) {
throw new Error('Cannot send request to registered endpoint if the user is not authenticated.');
}
// if the endpoint is registered then acquire and inject token
let headers = req.headers || new HttpHeaders();
return this.adal.acquireToken(resource).pipe(
mergeMap((token: string) => {
// inject the header
headers = headers.append('Authorization', 'Bearer ' + token);
return next.handle(req.clone({ headers: headers }));
}
)
)
}
}