Adding HTTP Interceptor for an unauthorized access in Angular

 The idea is to catch the 403 or 401 responses, and redirect the user to some informative page saying he has no access.

import { Injectable } from '@angular/core';

import {  HttpRequest,  HttpHandler,  HttpEvent,  HttpInterceptor,  HttpErrorResponse} from '@angular/common/http';

import { Observable, of, throwError } from 'rxjs';
import {catchError} from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable()
export class AuthInterceptorInterceptor implements HttpInterceptor {

  constructor(private router: Router) {}

  private handleAuthError(err: HttpErrorResponse): Observable<any> {

    if (err.status === 401 || err.status === 403) {
        this.router.navigate(['/unauthorized']);
        return of(err.message); // or nothing
    }

    return throwError(err);
}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(catchError(x => this.handleAuthError(x)));
  }

}

Now this interceptor should be provided in the app module:
providers: [{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorInterceptor, multi: true },],

Post a Comment

Previous Post Next Post