How do I need to set up this HttpInterceptor
? oidcSecurityService
is not defined.
The HttpClient
allows you to write interceptors. A common usecase would be to intercept any outgoing HTTP request and add an authorization header. Keep in mind that injecting OidcSecurityService
into the interceptor via the constructor results in a cyclic dependency. To avoid this use the injector instead.
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private oidcSecurityService: OidcSecurityService;
constructor(private injector: Injector) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let requestToForward = req;
if (this.oidcSecurityService === undefined) {
this.oidcSecurityService = this.injector.get(OidcSecurityService);
}
if (this.oidcSecurityService !== undefined) {
let token = this.oidcSecurityService.getToken();
if (token !== '') {
let tokenValue = 'Bearer ' + token;
requestToForward = req.clone({ setHeaders: { Authorization: tokenValue } });
}
} else {
console.debug('OidcSecurityService undefined: NO auth header!');
}
return next.handle(requestToForward);
}
}
This is in my app.module.
I need to get the OidcSecurityService
injected.
providers: [
OidcSecurityService,
OidcConfigService,
{
provide: APP_INITIALIZER,
useFactory: loadConfig,
deps: [OidcConfigService],
multi: true
},
AuthorizationGuard,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
]