Angular 4.3 - HTTP Interceptor - refresh JWT token

前端 未结 4 611
清酒与你
清酒与你 2020-12-29 14:50

I need to react (in interceptor class) on 403 Forbidden HTTP status (to obtain/refresh) JWT token and retry the request with fresh token.

In the code below, when ser

4条回答
  •  别那么骄傲
    2020-12-29 14:59

    Just wanted to share what worked for me:

    @Injectable()
    export class AutoReLoginInterceptor implements HttpInterceptor {
    
        constructor() {
        }
    
        intercept(req: HttpRequest, next: HttpHandler): Observable> {
            // as we want to intercept the possible errors, instead of directly returning the request execution, we return an Observable to control EVERYTHING
            return new Observable>(subscriber => {
    
                // first try for the request
                next.handle(req)
                    .subscribe((event: HttpEvent) => {
                            if (event instanceof HttpResponse) {
                                // the request went well and we have valid response
                                // give response to user and complete the subscription
                                subscriber.next(event);
                                subscriber.complete();
                            }
                        },
                        error => {
                            if (error instanceof HttpErrorResponse && error.status === 401) {
                                console.log('401 error, trying to re-login');
    
                                // try to re-log the user
                                this.reLogin().subscribe(authToken => {
                                    // re-login successful -> create new headers with the new auth token
                                    let newRequest = req.clone({
                                        headers: req.headers.set('Authorization', authToken)
                                    });
    
                                    // retry the request with the new token
                                    next.handle(newRequest)
                                        .subscribe(newEvent => {
                                            if (newEvent instanceof HttpResponse) {
                                                // the second try went well and we have valid response
                                                // give response to user and complete the subscription
                                                subscriber.next(newEvent);
                                                subscriber.complete();
                                            }
                                        }, error => {
                                            // second try went wrong -> throw error to subscriber
                                            subscriber.error(error);
                                        });
                                });
                            } else {
                                // the error was not related to auth token -> throw error to subscriber
                                subscriber.error(error);
                            }
                        });
            });
    
        }
    
        /**
         * Try to re-login the user.
         */
        private reLogin(): Observable {
            // obtain new authorization token and return it
        }
    }
    

提交回复
热议问题