In my Angular13 application with OAuth authentication, I am encountering issues when trying to add the token for all services.
I have been unsuccessful in managing the undefined token. Despite trying various techniques to retrieve the token, I always encounter errors. However, I still want to be able to utilize non-authenticated services.
@Injectable({
providedIn: 'root',
})
export class TokenInterceptorService implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const {token} = this.authService.decodedAccessToken;
if (token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
}
return next.handle(request).pipe(
catchError((err) => {
console.error(err);
const error = err.error.message || err.statusText;
return throwError(error);
})
);
}
}
I have added this on ngModel
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptorService,
multi: true,
},],
Attempted fixes:
const token = this.authService.decodedAccessToken;
// or this
typeof token != 'undefined' && token
// no condition
Authorization: `Bearer ${this.authService.decodedAccessToken}`,
// and on error 401
this.authService.logout();
//
return next.handle(request):
angular-oauth2-oidc.mjs:1398 error loading discovery document TypeError: Cannot destructure property 'token' of 'this.authService.decodedAccessToken' as it is undefined.
/// or
core.mjs:6509 ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of null (reading 'message')
/// or
status: 401
As a result, I am experiencing blank pages or incomplete loading on my application.