-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathadal.interceptor.ts
44 lines (36 loc) · 1.66 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
39
40
41
42
43
44
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: AdalService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// if the endpoint is not registered
// or if the header 'skip-adal' is set
// then pass the request as it is to the next handler
const resource = this.adal.getResourceForEndpoint(request.url);
const skipAdal = request.headers.get('skip-adal');
if (!resource || skipAdal) {
return next.handle(request);
}
// 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
return this.adal.acquireToken(resource)
.pipe(
mergeMap((token: string) => {
// clone the request and replace the original headers with
// cloned headers, updated with the authorization
const authorizedRequest = request.clone({
headers: request.headers.set('Authorization', 'Bearer ' + token),
});
return next.handle(authorizedRequest);
}
)
)
}
}