How to add token authentication in the headers with interceptor and the token can be null?

Viewed 48

I have Application Angular13 with authentication OAuth and I try to add this token for all services.

But I don't manage undefined token. I have tried several techniques for calling the token but I always end up with an error, I want to be able to use non-authenticate services anyway

@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 add this on ngModel

providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptorService,
    multi: true,
  },],

try this

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

I currently have blank pages or incomplete loading

1 Answers

Try this:

const token  = this.authService.decodedAccessToken?.token || null;
Related