-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathauth-interceptor.service.ts
More file actions
48 lines (41 loc) · 1.46 KB
/
Copy pathauth-interceptor.service.ts
File metadata and controls
48 lines (41 loc) · 1.46 KB
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
45
46
47
48
import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpHeaders } from '@angular/common/http';
import { Observable, from, lastValueFrom } from 'rxjs';
import { Constants } from '../constants';
@Injectable({
providedIn: 'root'
})
export class AuthInterceptorService implements HttpInterceptor {
constructor(private _authService: AuthService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if(req.url.startsWith(Constants.apiRoot)){
return this.interceptRequestWithAccessToken(req, next);
}
else {
return next.handle(req);
}
}
interceptRequestWithAccessToken(request: HttpRequest<any>, next: HttpHandler) {
return from(
this._authService.getAccessToken()
.then(accessToken => {
if (!accessToken) {
this._authService.signinSilent().then(user => {
return this.updateRequestHeader(request, next, user.access_token);
});
} else {
return this.updateRequestHeader(request, next, accessToken);
}
})
);
}
updateRequestHeader(request: HttpRequest<any>, next: HttpHandler, accessToken: string) {
const headerss = request.headers.set(
"Authorization",
`Bearer ${accessToken}`
);
const authReq = request.clone({ headers: headerss });
return lastValueFrom(next.handle(authReq));
}
}