Angular 4.3 HttpInterceptor: how to send request?

I have an HttpInterceptor that adds a JWT token for every HTTP request. Now I would like to be able to respond to 401 responses that will happen as soon as the tox expires.

Something line by line:

  • Sends a request
  • A 401 returns
  • A login form will appear, the user enters their credentials
  • If the login is successful, the new token is saved
  • The original httpRequest is sent again with a new token

So far this is what I have:

// Imports [...]

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {

    constructor(private logger: LoggingService, private injector: Injector) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        // Handle request
        const authService = this.injector.get(AuthService);
        const authToken = authService.getToken();

        if (authToken) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${authService.getToken()}`
                }
            });
        }

        // Handle response
        return next.handle(request)
            .do(event => {
                if (event instanceof HttpResponse) {
                    this.logger.logDebug(event);
                }
            })
            .catch((err: HttpErrorResponse) => {

                if (err.status === 401) {
                    // MISSING IMPLEMENTATION HERE   
                } else {
                    this.logger.logError(this.extractErrorMessage(err));
                }

                return Observable.throw(err);
            });
    }

    private extractErrorMessage(err: HttpErrorResponse): string {
        return err.error && err.error.devMessage ? err.error.devMessage : err.message;
    }    
}

      

Before continuing, I have a few doubts:

  • Is it possible to re-send the request as is, or do I need to use the HttpClient (GET, POST ..) methods?
  • Can I inject HttpClient into HttpInterceptor? Is there a risk of infinite loops?
  • Is this the correct approach?

Alternatively, I thought about checking the validity of the token on the client side before each HTTP request is sent with a library like Auth0 angular2 -jwt. Thus, I do not have to resend the request, I just need to update its header with a new token.

This looks like a cleaner solution to me , despite the added time it takes to validate the token every time.

Any thoughts are appreciated.

+3


source to share





All Articles