48 lines
1.5 KiB
TypeScript
48 lines
1.5 KiB
TypeScript
|
import { Injectable, Injector, Inject } from '@angular/core';
|
||
|
import { DOCUMENT } from '@angular/common'
|
||
|
import { AppConfig } from "./app.config";
|
||
|
import {
|
||
|
HttpRequest,
|
||
|
HttpHandler,
|
||
|
HttpEvent,
|
||
|
HttpInterceptor
|
||
|
} from '@angular/common/http';
|
||
|
import { OAuthService } from 'angular-oauth2-oidc';
|
||
|
import { Observable } from 'rxjs';
|
||
|
|
||
|
@Injectable()
|
||
|
export class AccessTokenInterceptor implements HttpInterceptor {
|
||
|
private oauthService: OAuthService = null;
|
||
|
private audience: string[] = [];
|
||
|
private base: string;
|
||
|
|
||
|
constructor(private injector: Injector, private appConfig: AppConfig, @Inject(DOCUMENT) private document: any) {
|
||
|
this.base = document.location.href;
|
||
|
}
|
||
|
|
||
|
hasAudience(url: string): boolean {
|
||
|
let u = new URL(url,this.base);
|
||
|
for (let audience of this.audience) {
|
||
|
if (u.href.startsWith(audience)) return true;
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
||
|
if (this.oauthService && this.hasAudience(request.url)) {
|
||
|
request = request.clone({
|
||
|
setHeaders: {
|
||
|
Authorization: `Bearer ${this.oauthService.getAccessToken()}`
|
||
|
}
|
||
|
// Please uncomment the next line if you need to connect to the backend running in Docker.
|
||
|
//, url: `http://localhost:8082${request.url}`
|
||
|
});
|
||
|
} else {
|
||
|
this.oauthService = this.injector.get(OAuthService, null);
|
||
|
if(this.oauthService && this.oauthService.issuer) this.audience = (this.appConfig.getConfig("audience") as string).split(",");
|
||
|
}
|
||
|
return next.handle(request);
|
||
|
}
|
||
|
}
|
||
|
|