Currently working on developing an HR Manager app with Angular for the frontend and .NET for the backend. I encountered an issue while trying to set the type in the interceptor for HttpRequests.
auth.interceptor.service.ts
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, from, tap } from 'rxjs';
import { CoreModule } from './core.module';
import { AuthService } from './auth-service.component';
import { Constants } from '../constants';
import { Router } from '@angular/router';
@Injectable()
export class AuthInterceptorService implements HttpInterceptor {
constructor(
private _authService: AuthService,
private _router: Router,
) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url.startsWith(Constants.apiRoot)) {
return from(this._authService.getAccessToken().then(token => {
const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
const authReq = req.clone({ headers });
return next.handle(authReq).pipe(tap(_ => { }, error => {
var respError = error as HttpErrorResponse;
if (respError && (respError.status === 401 || respError.status === 403)) {
this._router.navigate(['/unauthorized']);
}
})).toPromise();
}));
} else {
return next.handle(req);
}
}
}
The AuthService is responsible for managing login, logout, token retrieval, and other necessary functions.
auth-service.component.ts
import { Injectable } from '@angular/core';
import { CoreModule } from './core.module';
import { UserManager, User } from 'oidc-client';
import { Constants } from '../constants';
import { Subject } from 'rxjs';
@Injectable()
export class AuthService {
private _userManager: UserManager;
private _user: User | undefined;
private _loginChangedSubject = new Subject<boolean>();
loginChanged = this._loginChangedSubject.asObservable();
constructor() {
const stsSettings = {
authority: 'https://localhost:5443/',
client_id: 'spa-client',
redirect_uri: `${Constants.clientRoot}signin-callback`,
scope: 'openid profile projects-api',
response: 'id_token token',
post_logout_redirect_uri: `${Constants.clientRoot}signout-callback`,
};
this._userManager = new UserManager(stsSettings);
}
// Remaining code for AuthService...
// Error message and error code details would be placed here
Upon further investigation, the error seems to be originating from the following code snippet:
return from(this._authService.getAccessToken().then(token => {
const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
const authReq = req.clone({ headers });
return next.handle(authReq).pipe(tap(_ => { }, error => {
var respError = error as HttpErrorResponse;
if (respError && (respError.status === 401 || respError.status === 403)) {
this._router.navigate(['/unauthorized']);
}
})).toPromise();
}));