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:
- Sends a request
- A 401 comes back
- A login form pops up, the user enters his credentials
- If the login is successful, a new token is saved
- 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:
- Is it possible to resend a request as-is, or do I have to use the HttpClient's methods (GET, POST..) ?
- Is it wise to inject a HttpClient into the HttpInterceptor ? Is there a risk of endless loops ?
- 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.