我正在尝试对项目实施JWT授权。我知道JWT的总体工作原理。
我正在使用HttpInterceptor在标题中注入授权令牌,该令牌可以按预期工作。
第二个HttpInterceptor正在处理错误响应。如果响应中包含授权错误(401),则会发出获取新访问令牌的请求,该请求也将起作用。用过期的访问令牌调用的所有请求都缓存在一个数组中,因此一旦有了新令牌,我就可以重新运行最后一个请求。我遵循了这个guide,但不幸的是它没有介绍如何重新运行缓存的请求。
有人可以提供retryFailedRequests的实现吗?
这是我的HttpInterceptor:
export class TokenRefreshService implements HttpInterceptor {
constructor(public restService: RestService,
private http: HttpClient) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
// redirect to the login route
// or show a modal
this.restService.collectFailedRequest(request);
var headers: HttpHeaders = new HttpHeaders({
"Authorization": "Bearer " + localStorage.getItem('refresh_token')
});
console.log("REFRESHING");
return this.http.post(API_URL + '/token/refresh', null, {headers: headers})
.subscribe(resp => {
localStorage.setItem("access_token", resp["access_token"]);
//MISSING PART: RERUN CACHED REQUESTS
});
}
}
});
}
}
rest.service.ts
export class RestService {
constructor(private http: HttpClient,
private router:Router) {
}
cachedRequests: Array<HttpRequest<any>> = [];
public collectFailedRequest(request): void {
this.cachedRequests.push(request);
}
public retryFailedRequests(): void {
console.log("RETRY")
console.log(this.cachedRequests[0].urlWithParams);
// retry the requests. this method can
// be called after the token is refreshed
}
getTasks(group_id: string) {
return this.http.get(API_URL + '/tasks/get/' + group_id)
}
...
我完全迷失了如何设计它,因此不胜感激。