Angular 4.3 HttpInterceptor: How to resend a request?

Viewed 981

I have a HttpInterceptor that adds a JWT token to every http request. Now I would like it to react to 401 responses that will happen as soon as the token expires.

Something along the lines of:

  1. Sends a request
  2. A 401 comes back
  3. A login form pops up, the user enters his credentials
  4. If the login is successful, a new token is saved
  5. The original httpRequest is sent again with the 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 I continue, I have a few doubts:

  1. Is it possible to resend a request as-is, or do I have to use the HttpClient's methods (GET, POST..) ?
  2. Is it wise to inject a HttpClient into the HttpInterceptor ? Is there a risk of endless loops ?
  3. Is this the right approach ?

Alternatively, I thought of checking the validity of the token on the client side before every http request is sent with a library like Auth0's angular2-jwt. That way, I don't have to resend the request, I would just have to update its header with the new token.

To me, this looks like a cleaner solution, despite the added time it takes to verify the token each time.

Any thoughts are welcome.

0 Answers
Related