我正在使用刷新令牌,以便在jwt令牌过期时重新记录用户。为了处理重新记录,我创建了一个中间件类。
令牌过期时,api服务器将返回错误代码498;如果没有令牌/无效令牌/无效的刷新令牌,则api将返回401。
要求新令牌的部分可以很好地工作(我可以使用新令牌构建新请求),但是我不明白为什么新请求响应永远不会回来。我认为return temp_next.handle(request);
就足够了……
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthenticationService } from '../services/authentication.service';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 498) {
console.log('Token expired', request.headers.getAll('Authorization'));
const currentUser = JSON.parse(localStorage.getItem('currentUser'));
const temp_next = next;
this.authenticationService.tryRelog(currentUser.username, currentUser.refresh_token, (new_jwt) => {
console.log('We got a new token after logging in', new_jwt);
const temp_jwt = new_jwt;
request = request.clone({
setHeaders: {
Authorization: `${temp_jwt}`
}
});
console.log('Retrying the request with new token', request.headers.getAll('Authorization'));
return temp_next.handle(request);
});
}
if (err.status === 401) {
console.log('We are not authorized here');
// auto logout if 401 response returned from api
this.authenticationService.logout();
location.reload(false);
}
if (err.status === 200) {
console.log('OK');
return;
}
const error = err.error.message || err.statusText;
return throwError(error);
}));
}
}