angular 2 http异常处理程序和jwt刷新

标签 angular http jwt angular2-observables

当我遇到某个异常时,我正在尝试刷新 JWT token ,当它是另一个异常时,我的 ErrorHandler 应该处理它们。

我有一段代码,一段代码用于 token 刷新,一段代码用于异常处理程序,但我无法以有效的方式组合它们。

问题是我不能抛出异常并用我的 ErrorHandler 在 observable 中捕获它。

这是我可以用来刷新 token 的代码。当失败时,它会检查错误代码是否为 token_expired,如果是,它将刷新 token 并重试请求。

export class HttpErrorService extends Http {

  constructor(backend: XHRBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs, disableRefresh = false): Observable<Response> {
      return super.request(url, options).catch((error: Response) => {
        // Refresh token on token_expired exception.
        if (!disableRefresh && error.status === 401 && error.json().error.code === 'token_expired') {
          return this.renewToken().flatMap((response) => {
            const res = response.json();
            // Replace the token in storage.
            localStorage.setItem('__token', res.data.token);

            // Replace request the token with the new one.
            if (url instanceof Request) {
              url.headers.set('Authorization', 'Bearer ' + res.data.token);
            } else if (options) {
              options.headers.set('Authorization', 'Bearer ' + res.data.token);
            }

            // To prevent a loop disable refreshing at the next request.
            return this.request(url, options, true);
          });
        }

        // Here I want to throw the exception.
        // I need to be able to catch it with my exception handler.
        // throw error; doesn't work.
        return Observable.throw(error);
      });
  }

  private getBaseUrl(): string {
    return environment.base_uri;
  };

  renewToken(): Observable<Response> {
    const headers = new Headers();
    headers.append('Authorization', 'Bearer ' + localStorage.getItem('__token'))

    return this.post(this.getBaseUrl() + '/auth/refresh', {}, {headers: headers});
  }
}

上述唯一不好的地方是我无法在我的异常处理程序中捕获异常。

以下代码可以抛出可被 ErrorHandler 捕获的异常。但是我不知道如何在一次调用中刷新 token ...

export class HttpErrorService extends Http {

  constructor(backend: XHRBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs, disableRefresh = false): Observable<Response> {
    return Observable.create(observer => {
      super.request(url, options).subscribe(
        res => observer.next(res),
        err => {
          if (!disableRefresh && err.status === 401 && err.json().error.code === 'token_expired') {
            // I can't return this.renewToken()...
          }
          observer.error(err);
          throw new HttpException(err); // this is getting catched by the ErrorHandler
        },
        () => observer.complete);
    });
  }

  private getBaseUrl(): string {
    return environment.base_uri;
  };

  renewToken(): Observable<Response> {
    const headers = new Headers();
    headers.append('Authorization', 'Bearer ' + localStorage.getItem('__token'))

    return this.post(this.getBaseUrl() + '/auth/refresh', {}, {headers: headers});
  }
}

我的错误处理程序只包含一个 console.log()
https://angular.io/api/core/ErrorHandler

我怎样才能让它工作?

最佳答案

几个小时后,我终于找到了解决方案!

export class HttpErrorService extends Http {

  constructor(backend: XHRBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs, disableRefresh = false): Observable<Response> {
    return Observable.create(observer => {
      super.request(url, options).retryWhen(attempts => this.retryRequest(attempts)).catch((error: Response) => {
        // Refresh token on token_expired exception.
        if (!disableRefresh && error.status === 401 && error.json().error.code === 'token_expired') {
          return this.renewToken().flatMap((response) => {
            const res = response.json();
            // Replace the token in storage.
            localStorage.setItem('__token', res.data.token);

            // Replace request the token with the new one.
            if (url instanceof Request) {
              url.headers.set('Authorization', 'Bearer ' + res.data.token);
            } else if (options) {
              options.headers.set('Authorization', 'Bearer ' + res.data.token);
            }

            // To prevent a loop disable refreshing at the next request.
            return this.request(url, options, true);
          });
        }

        throw Observable.throw(error);
      }).subscribe(
        res => observer.next(res),
        err => {
          observer.error(err);
          throw new HttpException(err);
        }
      );
    });
  }

  private getBaseUrl(): string {
    return environment.base_uri;
  };

  renewToken(): Observable<Response> {
    const headers = new Headers();
    headers.append('Authorization', 'Bearer ' + localStorage.getItem('__token'))

    return this.post(this.getBaseUrl() + '/auth/refresh', {}, {headers: headers});
  }

  retryRequest(attempts: any) {
    let count = 0;

    return attempts.flatMap(error => {
        return ++count >= 3 ? Observable.throw(error) : Observable.timer(count * 1000);
    });
  }

}

关于angular 2 http异常处理程序和jwt刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45693820/

相关文章:

java - 无效的 RSA 私钥 : Keystore operation failed

html - 使用 innerHtml 在 div 中显示 HTML 字符串

php - Ajax 问题,变量没有被发送

javascript - 有效的 JWT 对于 NestJS 防护无效

java - 无法使用 HTTP 客户端传输图像

javascript - XMLHttpRequest 无法加载 http ://abc. mydomain.org/data/todo.js

authentication - ASP.NET Core 是否支持刷新 token ?

javascript - 将Promise对象设置为img [src]会将图像设置为null。有时

angular - 如何在页面初始化时翻译用 ngif 隐藏的文本?

css - Angular 2 创建的 Svg 无法缩放