Angular JWT在请求之前刷新令牌

时间:2019-12-04 14:23:31

标签: angular typescript jwt

您好,我正在尝试在请求之前刷新令牌。它是一个角度拦截器。我正在检查令牌是否过期,然后刷新。即使添加了take(1),Somitimes刷新工作的次数也增加了两倍。有时刷新后,主请求会立即生效,并且系统无法接受新令牌。

import {Inject, Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, of, throwError, timer} from 'rxjs';
import {AuthService} from '../Services/auth.service';
import {catchError, delay, flatMap, switchMap, take} from 'rxjs/operators';
import {HttpErrorHandlerService} from '../Services/http-error-handler.service';
import {InternalApiService} from '@common-lib';
import {JwtHelperService, JwtInterceptor} from '@auth0/angular-jwt';

@Injectable({
  providedIn: 'root'
})

export class HttpInterceptorService implements HttpInterceptor {
isRefreshing = false;

 constructor(@Inject('BASE_URL') private baseUrl: string,
          private authService: AuthService,
          private internalApiService: InternalApiService,
          private httpErrorHandlerService: HttpErrorHandlerService) {
}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let apiRequest;
const refresh_token = this.authService.getRefreshToken();

apiRequest = req.clone({url: `${this.baseUrl}${req.url}`});

if (this.authService.isTokenExpired() && !this.isRefreshing) {
  this.isRefreshing = true;
  return this.internalApiService.refreshToken({refresh_token})
    .pipe(
      take(1),
      flatMap((jwt) => {
        this.isRefreshing = false;
        apiRequest = apiRequest.clone({headers: apiRequest.headers.append('Authorization', `Bearer ${jwt.token}`)});
        return next.handle(apiRequest);
      })
    );
} else {
  return timer(this.isRefreshing ? 2000 : 0)
    .pipe(switchMap(() => next.handle(apiRequest)));
}

}
}

0 个答案:

没有答案