Angular 4.3 - HTTP Interceptor - refresh JWT token

前端 未结 4 645
清酒与你
清酒与你 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 15:01

    You need to add the catch operator from RxJS. This is where an error will be, and you can handle it accordingly.

    When you get an error of status 0, that most likely means the remote server is down and the connection could not be made.

    Take a look at my example logic:

    this.http.request(url, options)
            .map((res: Response) => res.json())
            .catch((error: any) => {
                const err = error.json();
    
                // Refresh JWT
                if (err.status === 403) {
                    // Add your token refresh logic here.
                }
    
                return Observable.throw(err);
            });
    

    In order to get your refresh logic to go through the interceptor, you need to return the invocation, and the function should also return an Observable. For example modifying the original logic above:

    this.http.request(url, options)
            .map((res: Response) => res.json())
            .catch((error: any) => {
                const err = error.json();
    
                // Refresh JWT
                if (err.status === 403) {
                    // refreshToken makes another HTTP call and returns an Observable.
                    return this.refreshToken(...);
                }
    
                return Observable.throw(err);
            });
    

    If you want to be able to retry the original request, what you can do is pass the original request data so that on successfully refreshing the token you can make the call again. For example, this is what your refreshToken function could look like:

    refreshToken(url: stirng, options: RequestOptionsArgs, body: any, tokenData: any): Observable
        return this.post(`${this.url}/token/refresh`, tokenData)
            .flatMap((res: any) => {
                // This is where I retry the original request
                return this.request(url, options, body);
            });
    }
    

提交回复
热议问题