我正在Angular 7应用程序中使用刷新令牌拦截器。我有一个jwt拦截器,它向每个请求添加授权令牌。现在,我想发送不带授权载体的刷新令牌,因为API不需要授权载体。
现在的问题是,刷新令牌请求与过期的令牌一起作为授权承载发送。但是服务器不需要过期的访问令牌作为授权载体。任何帮助将不胜感激。
这是我的刷新令牌方法。
refreshToken() {
const token = localStorage.getItem('refresh_token');
return this.http.post(`${environment.apiUrl}/token/refresh`, { 'refresh_token': token }, {headers: {}})
.pipe(
map(res => {
this.tokenPayload = res;
this.tokenPayload = this.tokenPayload.data.access_token;
if (res) {
localStorage.setItem('access_token', JSON.stringify(this.tokenPayload));
}
return this.tokenPayload;
}));
}
这是我的JWT拦截器。
isRefreshingToken = false;
tokenSubject: BehaviorSubject<string> = new BehaviorSubject<string>(null);
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent
| HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any> | any> {
return next.handle(this.addTokenToRequest(request, this.authService.getAuthToken()))
.pipe(
catchError(err => {
if (err instanceof HttpErrorResponse) {
switch ((<HttpErrorResponse>err).status) {
case 401:
return this.handle401Error(request, next);
case 400:
return <any>this.authService.logout();
}
} else {
return throwError(err);
}
}));
}
private addTokenToRequest(request: HttpRequest<any>, token: string): HttpRequest<any> {
return request.clone({ setHeaders: { Authorization: `Bearer ${token}`}});
}
private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
if(!this.isRefreshingToken) {
this.isRefreshingToken = true;
// Reset here so that the following requests wait until the token
// comes back from the refreshToken call.
this.tokenSubject.next(null);
return this.authService.refreshToken()
.pipe(
switchMap((token) => {
if(token) {
this.tokenSubject.next(JSON.stringify(token));
localStorage.setItem('access_token', JSON.stringify(token));
return next.handle(this.addTokenToRequest(request, JSON.stringify(token)));
}
return <any>this.authService.logout();
}),
catchError(err => {
return <any>this.authService.logout();
}),
finalize(() => {
this.isRefreshingToken = false;
})
);
} else {
this.isRefreshingToken = false;
return this.tokenSubject
.pipe(filter(token => token != null),
take(1),
switchMap(token => {
return next.handle(this.addTokenToRequest(request, token));
}));
}
}