令牌更新后,Angular 6在重新制作请求之前更改JWT令牌

时间:2019-05-20 10:41:25

标签: javascript angular typescript rxjs jwt

当令牌过期时,我正在使用JWT身份验证端(后端会对其进行检查),我必须调用刷新令牌API,并使上一次调用失败,因为令牌已过期。
我已经有了拦截器,但是在发出请求之前必须更新身份验证标头,并且必须等待refreshToken调用。

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const { shouldRetry } = this;
    return next.handle(request).pipe(  
      retryWhen(genericRetryStrategy({
        shouldRetry
      })),

      catchError(err => {
        //401 the token is invalid so I have to refresh it
        if (err.status === 401) {
          this.auth.refreshToken().subscribe(
            (apiResult: SessionTokenResponse) => {
              this.auth.saveToken(apiResult.token);
            },
            error => this.auth.logout()
          );
          request = request.clone({headers: request.headers.set('Authorization', 'Bearer ' + this.auth.getSessionToken)});
          return next.handle(request);
        }
        const error = err.error.message || err.statusText;
        return throwError(error);
      }),
    )
  }

重新拨打电话是否正确?如何等待refreshToken的结尾?谢谢

编辑:我已更新了似乎有效的代码,正在对其进行测试

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const { shouldRetry } = this;
return next.handle(request).pipe(
  retryWhen(genericRetryStrategy({
    shouldRetry
  })),

  catchError(err => {
    //401 the token is invalid so I have to refresh it
    if (err.status === 401) {
      this.auth.refreshToken().subscribe(
        (apiResult: SessionTokenResponse) => {
          this.auth.saveToken(apiResult.token);
          request = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + apiResult.token) });
          next.handle(request).subscribe();
        },
        err => this.auth.logout()
      );          
    }else{
      const error = err.error.message || err.statusText;
      return throwError(error);
    }
  }),
)

}

1 个答案:

答案 0 :(得分:0)

如果我的问题很好,您可以使用async等待刷新令牌 您可以检查当前令牌的访问权限,或者在CanActivate中刷新当前令牌的访问权限,顺便说一句,在每次请求时,它都会检查Access中的令牌,而无需在interceptor

在身份验证服务中

     async isAuthenticated(){
     const response = await this.auth.refreshToken().toPromise();
     return response;
  }

在CanActivate中

async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.authenticated= await this.Service.isAuthenticated();
    if(this.authenticated) {
         this.auth.saveToken(apiResult.token);
         return true;
      }
    else
        this.auth.logout();
        // navigate to login

}